three.webgpu.nodes.js 2.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649
  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, error, EventDispatcher, MathUtils, warn, WebGLCoordinateSystem, WebGPUCoordinateSystem, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBufferAttribute, InterleavedBuffer, DynamicDrawUsage, NoColorSpace, log as log$1, warnOnce, Texture, UnsignedIntType, IntType, Compatibility, LessCompare, LessEqualCompare, GreaterCompare, GreaterEqualCompare, NearestFilter, Sphere, BackSide, DoubleSide, CubeTexture, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, NoNormalPacking, NormalRGPacking, NormalGAPacking, ObjectSpaceNormalMap, RGFormat, 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, AlphaFormat, RedFormat, RedIntegerFormat, DepthFormat, DepthStencilFormat, RGIntegerFormat, RGBFormat, RGBIntegerFormat, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedInt101111Type, NormalBlending, SrcAlphaFactor, OneMinusSrcAlphaFactor, AddEquation, MaterialBlending, Object3D, LinearMipMapLinearFilter, Plane, Float32BufferAttribute, UVMapping, PCFShadowMap, PCFSoftShadowMap, VSMShadowMap, BasicShadowMap, CubeDepthTexture, SphereGeometry, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, yieldToMain, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, 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.getLights(), [] );
  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.getLights(), 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 value/object for the given data type and parameters.
  793. *
  794. * @private
  795. * @method
  796. * @param {string} type - The given type.
  797. * @param {...any} params - A parameter list.
  798. * @return {any} The value/object.
  799. */
  800. function getValueFromType( type, ...params ) {
  801. const last4 = type ? type.slice( -4 ) : undefined;
  802. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  803. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  804. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  805. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  806. }
  807. if ( type === 'color' ) {
  808. return new Color( ...params );
  809. } else if ( last4 === 'vec2' ) {
  810. return new Vector2( ...params );
  811. } else if ( last4 === 'vec3' ) {
  812. return new Vector3( ...params );
  813. } else if ( last4 === 'vec4' ) {
  814. return new Vector4( ...params );
  815. } else if ( last4 === 'mat2' ) {
  816. return new Matrix2( ...params );
  817. } else if ( last4 === 'mat3' ) {
  818. return new Matrix3( ...params );
  819. } else if ( last4 === 'mat4' ) {
  820. return new Matrix4( ...params );
  821. } else if ( type === 'bool' ) {
  822. return params[ 0 ] || false;
  823. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  824. return params[ 0 ] || 0;
  825. } else if ( type === 'string' ) {
  826. return params[ 0 ] || '';
  827. } else if ( type === 'ArrayBuffer' ) {
  828. return base64ToArrayBuffer( params[ 0 ] );
  829. }
  830. return null;
  831. }
  832. /**
  833. * Gets the object data that can be shared between different rendering steps.
  834. *
  835. * @private
  836. * @param {Object} object - The object to get the data for.
  837. * @return {Object} The object data.
  838. */
  839. function getDataFromObject( object ) {
  840. let data = dataFromObject.get( object );
  841. if ( data === undefined ) {
  842. data = {};
  843. dataFromObject.set( object, data );
  844. }
  845. return data;
  846. }
  847. /**
  848. * Converts the given array buffer to a Base64 string.
  849. *
  850. * @private
  851. * @method
  852. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  853. * @return {string} The Base64 string.
  854. */
  855. function arrayBufferToBase64( arrayBuffer ) {
  856. let chars = '';
  857. const array = new Uint8Array( arrayBuffer );
  858. for ( let i = 0; i < array.length; i ++ ) {
  859. chars += String.fromCharCode( array[ i ] );
  860. }
  861. return btoa( chars );
  862. }
  863. /**
  864. * Converts the given Base64 string to an array buffer.
  865. *
  866. * @private
  867. * @method
  868. * @param {string} base64 - The Base64 string.
  869. * @return {ArrayBuffer} The array buffer.
  870. */
  871. function base64ToArrayBuffer( base64 ) {
  872. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  873. }
  874. var NodeUtils = /*#__PURE__*/Object.freeze({
  875. __proto__: null,
  876. arrayBufferToBase64: arrayBufferToBase64,
  877. base64ToArrayBuffer: base64ToArrayBuffer,
  878. getAlignmentFromType: getAlignmentFromType,
  879. getDataFromObject: getDataFromObject,
  880. getLengthFromType: getLengthFromType,
  881. getMemoryLengthFromType: getMemoryLengthFromType,
  882. getTypeFromLength: getTypeFromLength,
  883. getTypedArrayFromType: getTypedArrayFromType,
  884. getValueFromType: getValueFromType,
  885. getValueType: getValueType,
  886. hash: hash$1,
  887. hashArray: hashArray,
  888. hashString: hashString
  889. });
  890. /**
  891. * Possible shader stages.
  892. *
  893. * @property {string} VERTEX The vertex shader stage.
  894. * @property {string} FRAGMENT The fragment shader stage.
  895. */
  896. const NodeShaderStage = {
  897. VERTEX: 'vertex',
  898. FRAGMENT: 'fragment'
  899. };
  900. /**
  901. * Update types of a node.
  902. *
  903. * @property {string} NONE The update method is not executed.
  904. * @property {string} FRAME The update method is executed per frame.
  905. * @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.
  906. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  907. */
  908. const NodeUpdateType = {
  909. NONE: 'none',
  910. FRAME: 'frame',
  911. RENDER: 'render',
  912. OBJECT: 'object'
  913. };
  914. /**
  915. * Data types of a node.
  916. *
  917. * @property {string} BOOLEAN Boolean type.
  918. * @property {string} INTEGER Integer type.
  919. * @property {string} FLOAT Float type.
  920. * @property {string} VECTOR2 Two-dimensional vector type.
  921. * @property {string} VECTOR3 Three-dimensional vector type.
  922. * @property {string} VECTOR4 Four-dimensional vector type.
  923. * @property {string} MATRIX2 2x2 matrix type.
  924. * @property {string} MATRIX3 3x3 matrix type.
  925. * @property {string} MATRIX4 4x4 matrix type.
  926. */
  927. const NodeType = {
  928. BOOLEAN: 'bool',
  929. INTEGER: 'int',
  930. FLOAT: 'float',
  931. VECTOR2: 'vec2',
  932. VECTOR3: 'vec3',
  933. VECTOR4: 'vec4',
  934. MATRIX2: 'mat2',
  935. MATRIX3: 'mat3',
  936. MATRIX4: 'mat4'
  937. };
  938. /**
  939. * Access types of a node. These are relevant for compute and storage usage.
  940. *
  941. * @property {string} READ_ONLY Read-only access
  942. * @property {string} WRITE_ONLY Write-only access.
  943. * @property {string} READ_WRITE Read and write access.
  944. */
  945. const NodeAccess = {
  946. READ_ONLY: 'readOnly',
  947. WRITE_ONLY: 'writeOnly',
  948. READ_WRITE: 'readWrite',
  949. };
  950. const defaultShaderStages = [ 'fragment', 'vertex' ];
  951. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  952. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  953. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  954. const _parentBuildStage = {
  955. analyze: 'setup',
  956. generate: 'analyze'
  957. };
  958. let _nodeId = 0;
  959. /**
  960. * Base class for all nodes.
  961. *
  962. * @augments EventDispatcher
  963. */
  964. class Node extends EventDispatcher {
  965. static get type() {
  966. return 'Node';
  967. }
  968. /**
  969. * Constructs a new node.
  970. *
  971. * @param {?string} nodeType - The node type.
  972. */
  973. constructor( nodeType = null ) {
  974. super();
  975. /**
  976. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  977. *
  978. * @type {?string}
  979. * @default null
  980. */
  981. this.nodeType = nodeType;
  982. /**
  983. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  984. *
  985. * @type {string}
  986. * @default 'none'
  987. */
  988. this.updateType = NodeUpdateType.NONE;
  989. /**
  990. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  991. *
  992. * @type {string}
  993. * @default 'none'
  994. */
  995. this.updateBeforeType = NodeUpdateType.NONE;
  996. /**
  997. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  998. *
  999. * @type {string}
  1000. * @default 'none'
  1001. */
  1002. this.updateAfterType = NodeUpdateType.NONE;
  1003. /**
  1004. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  1005. *
  1006. * @type {number}
  1007. * @readonly
  1008. * @default 0
  1009. */
  1010. this.version = 0;
  1011. /**
  1012. * The name of the node.
  1013. *
  1014. * @type {string}
  1015. * @default ''
  1016. */
  1017. this.name = '';
  1018. /**
  1019. * Whether this node is global or not. This property is relevant for the internal
  1020. * node caching system. All nodes which should be declared just once should
  1021. * set this flag to `true` (a typical example is {@link AttributeNode}).
  1022. *
  1023. * @type {boolean}
  1024. * @default false
  1025. */
  1026. this.global = false;
  1027. /**
  1028. * Create a list of parents for this node during the build process.
  1029. *
  1030. * @type {boolean}
  1031. * @default false
  1032. */
  1033. this.parents = false;
  1034. /**
  1035. * This flag can be used for type testing.
  1036. *
  1037. * @type {boolean}
  1038. * @readonly
  1039. * @default true
  1040. */
  1041. this.isNode = true;
  1042. // private
  1043. this._beforeNodes = null;
  1044. /**
  1045. * The cache key of this node.
  1046. *
  1047. * @private
  1048. * @type {?number}
  1049. * @default null
  1050. */
  1051. this._cacheKey = null;
  1052. /**
  1053. * The UUID of the node.
  1054. *
  1055. * @type {string}
  1056. * @default null
  1057. * @private
  1058. */
  1059. this._uuid = null;
  1060. /**
  1061. * The cache key's version.
  1062. *
  1063. * @private
  1064. * @type {number}
  1065. * @default 0
  1066. */
  1067. this._cacheKeyVersion = 0;
  1068. /**
  1069. * The unique ID of the node.
  1070. *
  1071. * @type {number}
  1072. * @readonly
  1073. */
  1074. this.id = _nodeId ++;
  1075. /**
  1076. * The stack trace of the node for debugging purposes.
  1077. *
  1078. * @type {?string}
  1079. * @default null
  1080. */
  1081. this.stackTrace = null;
  1082. if ( Node.captureStackTrace === true ) {
  1083. this.stackTrace = new StackTrace();
  1084. }
  1085. }
  1086. /**
  1087. * Set this property to `true` when the node should be regenerated.
  1088. *
  1089. * @type {boolean}
  1090. * @default false
  1091. * @param {boolean} value
  1092. */
  1093. set needsUpdate( value ) {
  1094. if ( value === true ) {
  1095. this.version ++;
  1096. }
  1097. }
  1098. /**
  1099. * The UUID of the node.
  1100. *
  1101. * @type {string}
  1102. * @readonly
  1103. */
  1104. get uuid() {
  1105. if ( this._uuid === null ) {
  1106. this._uuid = MathUtils.generateUUID();
  1107. }
  1108. return this._uuid;
  1109. }
  1110. /**
  1111. * The type of the class. The value is usually the constructor name.
  1112. *
  1113. * @type {string}
  1114. * @readonly
  1115. */
  1116. get type() {
  1117. return this.constructor.type;
  1118. }
  1119. /**
  1120. * Convenient method for defining {@link Node#update}.
  1121. *
  1122. * @param {Function} callback - The update method.
  1123. * @param {string} updateType - The update type.
  1124. * @return {Node} A reference to this node.
  1125. */
  1126. onUpdate( callback, updateType ) {
  1127. this.updateType = updateType;
  1128. this.update = callback.bind( this );
  1129. return this;
  1130. }
  1131. /**
  1132. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  1133. * this method automatically sets the update type to `FRAME`.
  1134. *
  1135. * @param {Function} callback - The update method.
  1136. * @return {Node} A reference to this node.
  1137. */
  1138. onFrameUpdate( callback ) {
  1139. return this.onUpdate( callback, NodeUpdateType.FRAME );
  1140. }
  1141. /**
  1142. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  1143. * this method automatically sets the update type to `RENDER`.
  1144. *
  1145. * @param {Function} callback - The update method.
  1146. * @return {Node} A reference to this node.
  1147. */
  1148. onRenderUpdate( callback ) {
  1149. return this.onUpdate( callback, NodeUpdateType.RENDER );
  1150. }
  1151. /**
  1152. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  1153. * this method automatically sets the update type to `OBJECT`.
  1154. *
  1155. * @param {Function} callback - The update method.
  1156. * @return {Node} A reference to this node.
  1157. */
  1158. onObjectUpdate( callback ) {
  1159. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  1160. }
  1161. /**
  1162. * Convenient method for defining {@link Node#updateReference}.
  1163. *
  1164. * @param {Function} callback - The update method.
  1165. * @return {Node} A reference to this node.
  1166. */
  1167. onReference( callback ) {
  1168. this.updateReference = callback.bind( this );
  1169. return this;
  1170. }
  1171. /**
  1172. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  1173. * to such objects based on a given state (e.g. the current node frame or builder).
  1174. *
  1175. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  1176. * @return {any} The updated reference.
  1177. */
  1178. updateReference( /*state*/ ) {
  1179. return this;
  1180. }
  1181. /**
  1182. * By default this method returns the value of the {@link Node#global} flag. This method
  1183. * can be overwritten in derived classes if an analytical way is required to determine the
  1184. * global cache referring to the current shader-stage.
  1185. *
  1186. * @param {NodeBuilder} builder - The current node builder.
  1187. * @return {boolean} Whether this node is global or not.
  1188. */
  1189. isGlobal( /*builder*/ ) {
  1190. return this.global;
  1191. }
  1192. /**
  1193. * Generator function that can be used to iterate over the child nodes.
  1194. *
  1195. * @generator
  1196. * @yields {Node} A child node.
  1197. */
  1198. * getChildren() {
  1199. for ( const { childNode } of this._getChildren() ) {
  1200. yield childNode;
  1201. }
  1202. }
  1203. /**
  1204. * Calling this method dispatches the `dispose` event. This event can be used
  1205. * to register event listeners for clean up tasks.
  1206. */
  1207. dispose() {
  1208. this.dispatchEvent( { type: 'dispose' } );
  1209. }
  1210. /**
  1211. * Callback for {@link Node#traverse}.
  1212. *
  1213. * @callback traverseCallback
  1214. * @param {Node} node - The current node.
  1215. */
  1216. /**
  1217. * Can be used to traverse through the node's hierarchy.
  1218. *
  1219. * @param {traverseCallback} callback - A callback that is executed per node.
  1220. */
  1221. traverse( callback ) {
  1222. callback( this );
  1223. for ( const childNode of this.getChildren() ) {
  1224. childNode.traverse( callback );
  1225. }
  1226. }
  1227. /**
  1228. * Returns the child nodes of this node.
  1229. *
  1230. * @private
  1231. * @param {Set<Node>} [ignores=new Set()] - A set of nodes to ignore during the search to avoid circular references.
  1232. * @returns {Array<Object>} An array of objects describing the child nodes.
  1233. */
  1234. _getChildren( ignores = new Set() ) {
  1235. const children = [];
  1236. // avoid circular references
  1237. ignores.add( this );
  1238. for ( const property of Object.getOwnPropertyNames( this ) ) {
  1239. const object = this[ property ];
  1240. // Ignore private properties and ignored nodes.
  1241. if ( property.startsWith( '_' ) === true || ignores.has( object ) ) continue;
  1242. if ( Array.isArray( object ) === true ) {
  1243. for ( let i = 0; i < object.length; i ++ ) {
  1244. const child = object[ i ];
  1245. if ( child && child.isNode === true ) {
  1246. children.push( { property, index: i, childNode: child } );
  1247. }
  1248. }
  1249. } else if ( object && object.isNode === true ) {
  1250. children.push( { property, childNode: object } );
  1251. } else if ( object && Object.getPrototypeOf( object ) === Object.prototype ) {
  1252. for ( const subProperty in object ) {
  1253. // Ignore private sub-properties.
  1254. if ( subProperty.startsWith( '_' ) === true ) continue;
  1255. const child = object[ subProperty ];
  1256. if ( child && child.isNode === true ) {
  1257. children.push( { property, index: subProperty, childNode: child } );
  1258. }
  1259. }
  1260. }
  1261. }
  1262. //
  1263. return children;
  1264. }
  1265. /**
  1266. * Returns the cache key for this node.
  1267. *
  1268. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1269. * @param {Set<Node>} [ignores=null] - A set of nodes to ignore during the computation of the cache key.
  1270. * @return {number} The cache key of the node.
  1271. */
  1272. getCacheKey( force = false, ignores = null ) {
  1273. force = force || this.version !== this._cacheKeyVersion;
  1274. if ( force === true || this._cacheKey === null ) {
  1275. if ( ignores === null ) ignores = new Set();
  1276. //
  1277. const values = [];
  1278. for ( const { property, childNode } of this._getChildren( ignores ) ) {
  1279. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey( force, ignores ) );
  1280. }
  1281. //
  1282. this._cacheKey = hash$1( hashArray( values ), this.customCacheKey() );
  1283. this._cacheKeyVersion = this.version;
  1284. }
  1285. return this._cacheKey;
  1286. }
  1287. /**
  1288. * Generate a custom cache key for this node.
  1289. *
  1290. * @return {number} The cache key of the node.
  1291. */
  1292. customCacheKey() {
  1293. return this.id;
  1294. }
  1295. /**
  1296. * Returns the references to this node which is by default `this`.
  1297. *
  1298. * @return {Node} A reference to this node.
  1299. */
  1300. getScope() {
  1301. return this;
  1302. }
  1303. /**
  1304. * Returns the hash of the node which is used to identify the node. By default it's
  1305. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1306. * depending on their implementation.
  1307. *
  1308. * @param {NodeBuilder} builder - The current node builder.
  1309. * @return {string} The hash.
  1310. */
  1311. getHash( /*builder*/ ) {
  1312. return String( this.id );
  1313. }
  1314. /**
  1315. * Returns the update type of {@link Node#update}.
  1316. *
  1317. * @return {NodeUpdateType} The update type.
  1318. */
  1319. getUpdateType() {
  1320. return this.updateType;
  1321. }
  1322. /**
  1323. * Returns the update type of {@link Node#updateBefore}.
  1324. *
  1325. * @return {NodeUpdateType} The update type.
  1326. */
  1327. getUpdateBeforeType() {
  1328. return this.updateBeforeType;
  1329. }
  1330. /**
  1331. * Returns the update type of {@link Node#updateAfter}.
  1332. *
  1333. * @return {NodeUpdateType} The update type.
  1334. */
  1335. getUpdateAfterType() {
  1336. return this.updateAfterType;
  1337. }
  1338. /**
  1339. * Certain types are composed of multiple elements. For example a `vec3`
  1340. * is composed of three `float` values. This method returns the type of
  1341. * these elements.
  1342. *
  1343. * @param {NodeBuilder} builder - The current node builder.
  1344. * @return {string} The type of the node.
  1345. */
  1346. getElementType( builder ) {
  1347. const type = this.getNodeType( builder );
  1348. const elementType = builder.getElementType( type );
  1349. return elementType;
  1350. }
  1351. /**
  1352. * Returns the node member type for the given name.
  1353. *
  1354. * @param {NodeBuilder} builder - The current node builder.
  1355. * @param {string} name - The name of the member.
  1356. * @return {string} The type of the node.
  1357. */
  1358. getMemberType( /*builder, name*/ ) {
  1359. return 'void';
  1360. }
  1361. /**
  1362. * Returns the node's type.
  1363. *
  1364. * @param {NodeBuilder} builder - The current node builder.
  1365. * @param {string} [output=null] - The output of the node.
  1366. * @return {string} The type of the node.
  1367. */
  1368. getNodeType( builder, output = null ) {
  1369. const nodeData = builder.getDataFromNode( this );
  1370. let type;
  1371. if ( output !== null ) {
  1372. nodeData.typeFromOutput = nodeData.typeFromOutput || {};
  1373. type = nodeData.typeFromOutput[ output ];
  1374. if ( type === undefined ) {
  1375. type = this.generateNodeType( builder, output );
  1376. nodeData.typeFromOutput[ output ] = type;
  1377. }
  1378. } else {
  1379. type = nodeData.type;
  1380. if ( type === undefined ) {
  1381. type = this.generateNodeType( builder );
  1382. nodeData.type = type;
  1383. }
  1384. }
  1385. return type;
  1386. }
  1387. /**
  1388. * Returns the node's type.
  1389. *
  1390. * @param {NodeBuilder} builder - The current node builder.
  1391. * @param {string} [output=null] - The output of the node.
  1392. * @return {string} The type of the node.
  1393. */
  1394. generateNodeType( builder, output = null ) {
  1395. const nodeProperties = builder.getNodeProperties( this );
  1396. if ( nodeProperties.outputNode ) {
  1397. return nodeProperties.outputNode.getNodeType( builder, output );
  1398. }
  1399. return this.nodeType;
  1400. }
  1401. /**
  1402. * This method is used during the build process of a node and ensures
  1403. * equal nodes are not built multiple times but just once. For example if
  1404. * `attribute( 'uv' )` is used multiple times by the user, the build
  1405. * process makes sure to process just the first node. It also handles
  1406. * node overrides if an override context is set.
  1407. *
  1408. * @param {NodeBuilder} builder - The current node builder.
  1409. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1410. */
  1411. getShared( builder ) {
  1412. const hash = this.getHash( builder );
  1413. const nodeFromHash = builder.getNodeFromHash( hash );
  1414. let sharedNode = null;
  1415. if ( nodeFromHash && nodeFromHash !== this ) {
  1416. sharedNode = nodeFromHash;
  1417. } else if ( builder.context.overrideNodes ) {
  1418. const callback = builder.context.overrideNodes.get( this );
  1419. if ( callback ) {
  1420. const nodeData = builder.getDataFromNode( this );
  1421. if ( nodeData.isOverwritten !== true ) {
  1422. nodeData.isOverwritten = true;
  1423. // cancel the override for use the same node inside the callback
  1424. sharedNode = callback( builder ).overrideNode( this, null );
  1425. nodeData.sharedNode = sharedNode;
  1426. } else {
  1427. // avoid recursive override calls
  1428. sharedNode = nodeData.sharedNode;
  1429. }
  1430. }
  1431. }
  1432. return sharedNode || this;
  1433. }
  1434. /**
  1435. * Returns the number of elements in the node array.
  1436. *
  1437. * @param {NodeBuilder} builder - The current node builder.
  1438. * @return {?number} The number of elements in the node array.
  1439. */
  1440. getArrayCount( /*builder*/ ) {
  1441. return null;
  1442. }
  1443. /**
  1444. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1445. * This method is often overwritten in derived modules to prepare the node which is used as a node's output/result.
  1446. * If an output node is prepared, then it must be returned in the `return` statement of the derived module's setup function.
  1447. *
  1448. * @param {NodeBuilder} builder - The current node builder.
  1449. * @return {?Node} The output node.
  1450. */
  1451. setup( builder ) {
  1452. const nodeProperties = builder.getNodeProperties( this );
  1453. let index = 0;
  1454. for ( const childNode of this.getChildren() ) {
  1455. nodeProperties[ 'node' + index ++ ] = childNode;
  1456. }
  1457. // return a outputNode if exists or null
  1458. return nodeProperties.outputNode || null;
  1459. }
  1460. /**
  1461. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1462. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1463. *
  1464. * @param {NodeBuilder} builder - The current node builder.
  1465. * @param {?Node} output - The target output node.
  1466. */
  1467. analyze( builder, output = null ) {
  1468. const usageCount = builder.increaseUsage( this );
  1469. if ( this.parents === true ) {
  1470. const nodeData = builder.getDataFromNode( this, 'any' );
  1471. nodeData.stages = nodeData.stages || {};
  1472. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1473. nodeData.stages[ builder.shaderStage ].push( output );
  1474. }
  1475. if ( usageCount === 1 ) {
  1476. // node flow children
  1477. const nodeProperties = builder.getNodeProperties( this );
  1478. for ( const childNode of Object.values( nodeProperties ) ) {
  1479. if ( childNode && childNode.isNode === true ) {
  1480. childNode.build( builder, this );
  1481. }
  1482. }
  1483. }
  1484. }
  1485. /**
  1486. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1487. * This state builds the output node and returns the resulting shader string.
  1488. *
  1489. * @param {NodeBuilder} builder - The current node builder.
  1490. * @param {?string} [output] - Can be used to define the output type.
  1491. * @return {?string} The generated shader string.
  1492. */
  1493. generate( builder, output ) {
  1494. const { outputNode } = builder.getNodeProperties( this );
  1495. if ( outputNode && outputNode.isNode === true ) {
  1496. return outputNode.build( builder, output );
  1497. }
  1498. }
  1499. /**
  1500. * The method can be implemented to update the node's internal state before it is used to render an object.
  1501. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1502. *
  1503. * @abstract
  1504. * @param {NodeFrame} frame - A reference to the current node frame.
  1505. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1506. */
  1507. updateBefore( /*frame*/ ) {
  1508. warn( 'Abstract function.' );
  1509. }
  1510. /**
  1511. * The method can be implemented to update the node's internal state after it was used to render an object.
  1512. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1513. *
  1514. * @abstract
  1515. * @param {NodeFrame} frame - A reference to the current node frame.
  1516. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1517. */
  1518. updateAfter( /*frame*/ ) {
  1519. warn( 'Abstract function.' );
  1520. }
  1521. /**
  1522. * The method can be implemented to update the node's internal state when it is used to render an object.
  1523. * The {@link Node#updateType} property defines how often the update is executed.
  1524. *
  1525. * @abstract
  1526. * @param {NodeFrame} frame - A reference to the current node frame.
  1527. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1528. */
  1529. update( /*frame*/ ) {
  1530. warn( 'Abstract function.' );
  1531. }
  1532. before( node ) {
  1533. if ( this._beforeNodes === null ) this._beforeNodes = [];
  1534. this._beforeNodes.push( node );
  1535. return this;
  1536. }
  1537. /**
  1538. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1539. * - **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.
  1540. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1541. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1542. *
  1543. * @param {NodeBuilder} builder - The current node builder.
  1544. * @param {?(string|Node)} [output=null] - Can be used to define the output type.
  1545. * @return {?(Node|string)} The result of the build process, depending on the build stage.
  1546. */
  1547. build( builder, output = null ) {
  1548. const refNode = this.getShared( builder );
  1549. if ( this !== refNode ) {
  1550. return refNode.build( builder, output );
  1551. }
  1552. //
  1553. if ( this._beforeNodes !== null ) {
  1554. const currentBeforeNodes = this._beforeNodes;
  1555. this._beforeNodes = null;
  1556. for ( const beforeNode of currentBeforeNodes ) {
  1557. beforeNode.build( builder, output );
  1558. }
  1559. this._beforeNodes = currentBeforeNodes;
  1560. }
  1561. //
  1562. const nodeData = builder.getDataFromNode( this );
  1563. nodeData.buildStages = nodeData.buildStages || {};
  1564. nodeData.buildStages[ builder.buildStage ] = true;
  1565. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1566. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1567. // force parent build stage (setup or analyze)
  1568. const previousBuildStage = builder.getBuildStage();
  1569. builder.setBuildStage( parentBuildStage );
  1570. this.build( builder );
  1571. builder.setBuildStage( previousBuildStage );
  1572. }
  1573. //
  1574. builder.addChain( this );
  1575. /* Build stages expected results:
  1576. - "setup" -> Node
  1577. - "analyze" -> null
  1578. - "generate" -> String
  1579. */
  1580. let result = null;
  1581. const buildStage = builder.getBuildStage();
  1582. if ( buildStage === 'setup' ) {
  1583. builder.addNode( this );
  1584. this.updateReference( builder );
  1585. const properties = builder.getNodeProperties( this );
  1586. if ( properties.initialized !== true ) {
  1587. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1588. properties.initialized = true;
  1589. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1590. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1591. // !! no outputNode !!
  1592. //outputNode = builder.stack;
  1593. }*/
  1594. for ( const childNode of Object.values( properties ) ) {
  1595. if ( childNode && childNode.isNode === true ) {
  1596. if ( childNode.parents === true ) {
  1597. const childProperties = builder.getNodeProperties( childNode );
  1598. childProperties.parents = childProperties.parents || [];
  1599. childProperties.parents.push( this );
  1600. }
  1601. childNode.build( builder );
  1602. }
  1603. }
  1604. builder.addSequentialNode( this );
  1605. }
  1606. result = properties.outputNode;
  1607. } else if ( buildStage === 'analyze' ) {
  1608. this.analyze( builder, output );
  1609. } else if ( buildStage === 'generate' ) {
  1610. // If generate has just one argument, it means the output type is not required.
  1611. // This means that the node does not handle output conversions internally,
  1612. // so the value is stored in a cache and the builder handles the conversion
  1613. // for all requested output types.
  1614. const isGenerateOnce = this.generate.length < 2;
  1615. if ( isGenerateOnce ) {
  1616. const type = this.getNodeType( builder );
  1617. const nodeData = builder.getDataFromNode( this );
  1618. result = nodeData.snippet;
  1619. if ( result === undefined ) {
  1620. if ( nodeData.generated === undefined ) {
  1621. nodeData.generated = true;
  1622. result = this.generate( builder ) || '';
  1623. nodeData.snippet = result;
  1624. } else {
  1625. warn( 'Node: Recursion detected.', this );
  1626. result = '/* Recursion detected. */';
  1627. }
  1628. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1629. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1630. }
  1631. result = builder.format( result, type, output );
  1632. } else {
  1633. result = this.generate( builder, output ) || '';
  1634. }
  1635. if ( result === '' && output !== null && output !== 'void' && output !== 'OutputType' ) {
  1636. // if no snippet is generated, return a default value
  1637. error( `TSL: Invalid generated code, expected a "${ output }".` );
  1638. result = builder.generateConst( output );
  1639. }
  1640. }
  1641. builder.removeChain( this );
  1642. return result;
  1643. }
  1644. /**
  1645. * Returns the child nodes as a JSON object.
  1646. *
  1647. * @return {Generator<Object>} An iterable list of serialized child objects as JSON.
  1648. */
  1649. getSerializeChildren() {
  1650. return this._getChildren();
  1651. }
  1652. /**
  1653. * Serializes the node to JSON.
  1654. *
  1655. * @param {Object} json - The output JSON object.
  1656. */
  1657. serialize( json ) {
  1658. const nodeChildren = this.getSerializeChildren();
  1659. const inputNodes = {};
  1660. for ( const { property, index, childNode } of nodeChildren ) {
  1661. if ( index !== undefined ) {
  1662. if ( inputNodes[ property ] === undefined ) {
  1663. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1664. }
  1665. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1666. } else {
  1667. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1668. }
  1669. }
  1670. if ( Object.keys( inputNodes ).length > 0 ) {
  1671. json.inputNodes = inputNodes;
  1672. }
  1673. }
  1674. /**
  1675. * Deserializes the node from the given JSON.
  1676. *
  1677. * @param {Object} json - The JSON object.
  1678. */
  1679. deserialize( json ) {
  1680. if ( json.inputNodes !== undefined ) {
  1681. const nodes = json.meta.nodes;
  1682. for ( const property in json.inputNodes ) {
  1683. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1684. const inputArray = [];
  1685. for ( const uuid of json.inputNodes[ property ] ) {
  1686. inputArray.push( nodes[ uuid ] );
  1687. }
  1688. this[ property ] = inputArray;
  1689. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1690. const inputObject = {};
  1691. for ( const subProperty in json.inputNodes[ property ] ) {
  1692. const uuid = json.inputNodes[ property ][ subProperty ];
  1693. inputObject[ subProperty ] = nodes[ uuid ];
  1694. }
  1695. this[ property ] = inputObject;
  1696. } else {
  1697. const uuid = json.inputNodes[ property ];
  1698. this[ property ] = nodes[ uuid ];
  1699. }
  1700. }
  1701. }
  1702. }
  1703. /**
  1704. * Serializes the node into the three.js JSON Object/Scene format.
  1705. *
  1706. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1707. * @return {Object} The serialized node.
  1708. */
  1709. toJSON( meta ) {
  1710. const { uuid, type } = this;
  1711. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1712. if ( isRoot ) {
  1713. meta = {
  1714. textures: {},
  1715. images: {},
  1716. nodes: {}
  1717. };
  1718. }
  1719. // serialize
  1720. let data = meta.nodes[ uuid ];
  1721. if ( data === undefined ) {
  1722. data = {
  1723. uuid,
  1724. type,
  1725. meta,
  1726. metadata: {
  1727. version: 4.7,
  1728. type: 'Node',
  1729. generator: 'Node.toJSON'
  1730. }
  1731. };
  1732. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1733. this.serialize( data );
  1734. delete data.meta;
  1735. }
  1736. // TODO: Copied from Object3D.toJSON
  1737. function extractFromCache( cache ) {
  1738. const values = [];
  1739. for ( const key in cache ) {
  1740. const data = cache[ key ];
  1741. delete data.metadata;
  1742. values.push( data );
  1743. }
  1744. return values;
  1745. }
  1746. if ( isRoot ) {
  1747. const textures = extractFromCache( meta.textures );
  1748. const images = extractFromCache( meta.images );
  1749. const nodes = extractFromCache( meta.nodes );
  1750. if ( textures.length > 0 ) data.textures = textures;
  1751. if ( images.length > 0 ) data.images = images;
  1752. if ( nodes.length > 0 ) data.nodes = nodes;
  1753. }
  1754. return data;
  1755. }
  1756. }
  1757. /**
  1758. * Enables or disables the automatic capturing of stack traces for nodes.
  1759. *
  1760. * @type {boolean}
  1761. * @default false
  1762. */
  1763. Node.captureStackTrace = false;
  1764. /**
  1765. * Base class for representing element access on an array-like
  1766. * node data structures.
  1767. *
  1768. * @augments Node
  1769. */
  1770. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1771. static get type() {
  1772. return 'ArrayElementNode';
  1773. }
  1774. /**
  1775. * Constructs an array element node.
  1776. *
  1777. * @param {Node} node - The array-like node.
  1778. * @param {Node} indexNode - The index node that defines the element access.
  1779. */
  1780. constructor( node, indexNode ) {
  1781. super();
  1782. /**
  1783. * The array-like node.
  1784. *
  1785. * @type {Node}
  1786. */
  1787. this.node = node;
  1788. /**
  1789. * The index node that defines the element access.
  1790. *
  1791. * @type {Node}
  1792. */
  1793. this.indexNode = indexNode;
  1794. /**
  1795. * This flag can be used for type testing.
  1796. *
  1797. * @type {boolean}
  1798. * @readonly
  1799. * @default true
  1800. */
  1801. this.isArrayElementNode = true;
  1802. }
  1803. /**
  1804. * This method is overwritten since the node type is inferred from the array-like node.
  1805. *
  1806. * @param {NodeBuilder} builder - The current node builder.
  1807. * @return {string} The node type.
  1808. */
  1809. generateNodeType( builder ) {
  1810. return this.node.getElementType( builder );
  1811. }
  1812. /**
  1813. * This method is overwritten since the member type is inferred from the array-like node.
  1814. *
  1815. * @param {NodeBuilder} builder - The current node builder.
  1816. * @param {string} name - The member name.
  1817. * @return {string} The member type.
  1818. */
  1819. getMemberType( builder, name ) {
  1820. return this.node.getMemberType( builder, name );
  1821. }
  1822. generate( builder ) {
  1823. const indexType = this.indexNode.getNodeType( builder );
  1824. const nodeSnippet = this.node.build( builder );
  1825. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1826. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1827. }
  1828. }
  1829. /**
  1830. * This module is part of the TSL core and usually not used in app level code.
  1831. * It represents a convert operation during the shader generation process
  1832. * meaning it converts the data type of a node to a target data type.
  1833. *
  1834. * @augments Node
  1835. */
  1836. class ConvertNode extends Node {
  1837. static get type() {
  1838. return 'ConvertNode';
  1839. }
  1840. /**
  1841. * Constructs a new convert node.
  1842. *
  1843. * @param {Node} node - The node which type should be converted.
  1844. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1845. */
  1846. constructor( node, convertTo ) {
  1847. super();
  1848. /**
  1849. * The node which type should be converted.
  1850. *
  1851. * @type {Node}
  1852. */
  1853. this.node = node;
  1854. /**
  1855. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1856. *
  1857. * @type {string}
  1858. */
  1859. this.convertTo = convertTo;
  1860. }
  1861. /**
  1862. * This method is overwritten since the implementation tries to infer the best
  1863. * matching type from the {@link ConvertNode#convertTo} property.
  1864. *
  1865. * @param {NodeBuilder} builder - The current node builder.
  1866. * @return {string} The node type.
  1867. */
  1868. generateNodeType( builder ) {
  1869. const requestType = this.node.getNodeType( builder );
  1870. let convertTo = null;
  1871. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1872. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1873. convertTo = overloadingType;
  1874. }
  1875. }
  1876. return convertTo;
  1877. }
  1878. serialize( data ) {
  1879. super.serialize( data );
  1880. data.convertTo = this.convertTo;
  1881. }
  1882. deserialize( data ) {
  1883. super.deserialize( data );
  1884. this.convertTo = data.convertTo;
  1885. }
  1886. generate( builder, output ) {
  1887. const node = this.node;
  1888. const type = this.getNodeType( builder );
  1889. const snippet = node.build( builder, type );
  1890. return builder.format( snippet, type, output );
  1891. }
  1892. }
  1893. /**
  1894. * This module uses cache management to create temporary variables
  1895. * if the node is used more than once to prevent duplicate calculations.
  1896. *
  1897. * The class acts as a base class for many other nodes types.
  1898. *
  1899. * @augments Node
  1900. */
  1901. class TempNode extends Node {
  1902. static get type() {
  1903. return 'TempNode';
  1904. }
  1905. /**
  1906. * Constructs a temp node.
  1907. *
  1908. * @param {?string} nodeType - The node type.
  1909. */
  1910. constructor( nodeType = null ) {
  1911. super( nodeType );
  1912. /**
  1913. * This flag can be used for type testing.
  1914. *
  1915. * @type {boolean}
  1916. * @readonly
  1917. * @default true
  1918. */
  1919. this.isTempNode = true;
  1920. }
  1921. /**
  1922. * Whether this node is used more than once in context of other nodes.
  1923. *
  1924. * @param {NodeBuilder} builder - The node builder.
  1925. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1926. */
  1927. hasDependencies( builder ) {
  1928. return builder.getDataFromNode( this ).usageCount > 1;
  1929. }
  1930. build( builder, output ) {
  1931. const buildStage = builder.getBuildStage();
  1932. if ( buildStage === 'generate' ) {
  1933. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1934. const nodeData = builder.getDataFromNode( this );
  1935. if ( nodeData.propertyName !== undefined ) {
  1936. return builder.format( nodeData.propertyName, type, output );
  1937. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1938. const snippet = super.build( builder, type );
  1939. const nodeVar = builder.getVarFromNode( this, null, type );
  1940. const propertyName = builder.getPropertyName( nodeVar );
  1941. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1942. nodeData.snippet = snippet;
  1943. nodeData.propertyName = propertyName;
  1944. return builder.format( nodeData.propertyName, type, output );
  1945. }
  1946. }
  1947. return super.build( builder, output );
  1948. }
  1949. }
  1950. /**
  1951. * This module is part of the TSL core and usually not used in app level code.
  1952. * It represents a join operation during the shader generation process.
  1953. * For example in can compose/join two single floats into a `vec2` type.
  1954. *
  1955. * @augments TempNode
  1956. */
  1957. class JoinNode extends TempNode {
  1958. static get type() {
  1959. return 'JoinNode';
  1960. }
  1961. /**
  1962. * Constructs a new join node.
  1963. *
  1964. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1965. * @param {?string} [nodeType=null] - The node type.
  1966. */
  1967. constructor( nodes = [], nodeType = null ) {
  1968. super( nodeType );
  1969. /**
  1970. * An array of nodes that should be joined.
  1971. *
  1972. * @type {Array<Node>}
  1973. */
  1974. this.nodes = nodes;
  1975. }
  1976. /**
  1977. * This method is overwritten since the node type must be inferred from the
  1978. * joined data length if not explicitly defined.
  1979. *
  1980. * @param {NodeBuilder} builder - The current node builder.
  1981. * @return {string} The node type.
  1982. */
  1983. generateNodeType( builder ) {
  1984. if ( this.nodeType !== null ) {
  1985. return builder.getVectorType( this.nodeType );
  1986. }
  1987. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1988. }
  1989. generate( builder, output ) {
  1990. const type = this.getNodeType( builder );
  1991. const maxLength = builder.getTypeLength( type );
  1992. const nodes = this.nodes;
  1993. const primitiveType = builder.getComponentType( type );
  1994. const snippetValues = [];
  1995. let length = 0;
  1996. for ( const input of nodes ) {
  1997. if ( length >= maxLength ) {
  1998. error( `TSL: Length of parameters exceeds maximum length of function '${ type }()' type.`, this.stackTrace );
  1999. break;
  2000. }
  2001. let inputType = input.getNodeType( builder );
  2002. let inputTypeLength = builder.getTypeLength( inputType );
  2003. let inputSnippet;
  2004. if ( length + inputTypeLength > maxLength ) {
  2005. error( `TSL: Length of '${ type }()' data exceeds maximum length of output type.`, this.stackTrace );
  2006. inputTypeLength = maxLength - length;
  2007. inputType = builder.getTypeFromLength( inputTypeLength );
  2008. }
  2009. length += inputTypeLength;
  2010. inputSnippet = input.build( builder, inputType );
  2011. const inputPrimitiveType = builder.getComponentType( inputType );
  2012. if ( inputPrimitiveType !== primitiveType ) {
  2013. const targetType = builder.getTypeFromLength( inputTypeLength, primitiveType );
  2014. inputSnippet = builder.format( inputSnippet, inputType, targetType );
  2015. }
  2016. snippetValues.push( inputSnippet );
  2017. }
  2018. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  2019. return builder.format( snippet, type, output );
  2020. }
  2021. }
  2022. const _stringVectorComponents = vectorComponents.join( '' );
  2023. /**
  2024. * This module is part of the TSL core and usually not used in app level code.
  2025. * `SplitNode` represents a property access operation which means it is
  2026. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  2027. * For example:
  2028. * ```js
  2029. * const redValue = color.r;
  2030. * ```
  2031. *
  2032. * @augments Node
  2033. */
  2034. class SplitNode extends Node {
  2035. static get type() {
  2036. return 'SplitNode';
  2037. }
  2038. /**
  2039. * Constructs a new split node.
  2040. *
  2041. * @param {Node} node - The node that should be accessed.
  2042. * @param {string} [components='x'] - The components that should be accessed.
  2043. */
  2044. constructor( node, components = 'x' ) {
  2045. super();
  2046. /**
  2047. * The node that should be accessed.
  2048. *
  2049. * @type {Node}
  2050. */
  2051. this.node = node;
  2052. /**
  2053. * The components that should be accessed.
  2054. *
  2055. * @type {string}
  2056. */
  2057. this.components = components;
  2058. /**
  2059. * This flag can be used for type testing.
  2060. *
  2061. * @type {boolean}
  2062. * @readonly
  2063. * @default true
  2064. */
  2065. this.isSplitNode = true;
  2066. }
  2067. /**
  2068. * Returns the vector length which is computed based on the requested components.
  2069. *
  2070. * @return {number} The vector length.
  2071. */
  2072. getVectorLength() {
  2073. let vectorLength = this.components.length;
  2074. for ( const c of this.components ) {
  2075. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  2076. }
  2077. return vectorLength;
  2078. }
  2079. /**
  2080. * Returns the component type of the node's type.
  2081. *
  2082. * @param {NodeBuilder} builder - The current node builder.
  2083. * @return {string} The component type.
  2084. */
  2085. getComponentType( builder ) {
  2086. return builder.getComponentType( this.node.getNodeType( builder ) );
  2087. }
  2088. /**
  2089. * This method is overwritten since the node type is inferred from requested components.
  2090. *
  2091. * @param {NodeBuilder} builder - The current node builder.
  2092. * @return {string} The node type.
  2093. */
  2094. generateNodeType( builder ) {
  2095. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  2096. }
  2097. /**
  2098. * Returns the scope of the node.
  2099. *
  2100. * @return {Node} The scope of the node.
  2101. */
  2102. getScope() {
  2103. return this.node.getScope();
  2104. }
  2105. generate( builder, output ) {
  2106. const node = this.node;
  2107. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  2108. let snippet = null;
  2109. if ( nodeTypeLength > 1 ) {
  2110. let type = null;
  2111. const componentsLength = this.getVectorLength();
  2112. if ( componentsLength >= nodeTypeLength ) {
  2113. // needed expand the input node
  2114. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  2115. }
  2116. const nodeSnippet = node.build( builder, type );
  2117. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  2118. // unnecessary swizzle
  2119. snippet = builder.format( nodeSnippet, type, output );
  2120. } else {
  2121. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  2122. }
  2123. } else {
  2124. // ignore .components if .node returns float/integer
  2125. snippet = node.build( builder, output );
  2126. }
  2127. return snippet;
  2128. }
  2129. serialize( data ) {
  2130. super.serialize( data );
  2131. data.components = this.components;
  2132. }
  2133. deserialize( data ) {
  2134. super.deserialize( data );
  2135. this.components = data.components;
  2136. }
  2137. }
  2138. /**
  2139. * This module is part of the TSL core and usually not used in app level code.
  2140. * `SetNode` represents a set operation which means it is used to implement any
  2141. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  2142. * For example:
  2143. * ```js
  2144. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  2145. * ```
  2146. *
  2147. * @augments TempNode
  2148. */
  2149. class SetNode extends TempNode {
  2150. static get type() {
  2151. return 'SetNode';
  2152. }
  2153. /**
  2154. * Constructs a new set node.
  2155. *
  2156. * @param {Node} sourceNode - The node that should be updated.
  2157. * @param {string} components - The components that should be updated.
  2158. * @param {Node} targetNode - The value node.
  2159. */
  2160. constructor( sourceNode, components, targetNode ) {
  2161. super();
  2162. /**
  2163. * The node that should be updated.
  2164. *
  2165. * @type {Node}
  2166. */
  2167. this.sourceNode = sourceNode;
  2168. /**
  2169. * The components that should be updated.
  2170. *
  2171. * @type {string}
  2172. */
  2173. this.components = components;
  2174. /**
  2175. * The value node.
  2176. *
  2177. * @type {Node}
  2178. */
  2179. this.targetNode = targetNode;
  2180. }
  2181. /**
  2182. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  2183. *
  2184. * @param {NodeBuilder} builder - The current node builder.
  2185. * @return {string} The node type.
  2186. */
  2187. generateNodeType( builder ) {
  2188. return this.sourceNode.getNodeType( builder );
  2189. }
  2190. generate( builder ) {
  2191. const { sourceNode, components, targetNode } = this;
  2192. const sourceType = this.getNodeType( builder );
  2193. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  2194. const targetType = builder.getTypeFromLength( components.length, componentType );
  2195. const targetSnippet = targetNode.build( builder, targetType );
  2196. const sourceSnippet = sourceNode.build( builder, sourceType );
  2197. const length = builder.getTypeLength( sourceType );
  2198. const snippetValues = [];
  2199. for ( let i = 0; i < length; i ++ ) {
  2200. const component = vectorComponents[ i ];
  2201. if ( component === components[ 0 ] ) {
  2202. snippetValues.push( targetSnippet );
  2203. i += components.length - 1;
  2204. } else {
  2205. snippetValues.push( sourceSnippet + '.' + component );
  2206. }
  2207. }
  2208. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  2209. }
  2210. }
  2211. /**
  2212. * This module is part of the TSL core and usually not used in app level code.
  2213. * It represents a flip operation during the shader generation process
  2214. * meaning it flips normalized values with the following formula:
  2215. * ```
  2216. * x = 1 - x;
  2217. * ```
  2218. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  2219. * `flipSTPQ()` method invocations on node objects. For example:
  2220. * ```js
  2221. * uvNode = uvNode.flipY();
  2222. * ```
  2223. *
  2224. * @augments TempNode
  2225. */
  2226. class FlipNode extends TempNode {
  2227. static get type() {
  2228. return 'FlipNode';
  2229. }
  2230. /**
  2231. * Constructs a new flip node.
  2232. *
  2233. * @param {Node} sourceNode - The node which component(s) should be flipped.
  2234. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  2235. */
  2236. constructor( sourceNode, components ) {
  2237. super();
  2238. /**
  2239. * The node which component(s) should be flipped.
  2240. *
  2241. * @type {Node}
  2242. */
  2243. this.sourceNode = sourceNode;
  2244. /**
  2245. * The components that should be flipped e.g. `'x'` or `'xy'`.
  2246. *
  2247. * @type {string}
  2248. */
  2249. this.components = components;
  2250. }
  2251. /**
  2252. * This method is overwritten since the node type is inferred from the source node.
  2253. *
  2254. * @param {NodeBuilder} builder - The current node builder.
  2255. * @return {string} The node type.
  2256. */
  2257. generateNodeType( builder ) {
  2258. return this.sourceNode.getNodeType( builder );
  2259. }
  2260. generate( builder ) {
  2261. const { components, sourceNode } = this;
  2262. const sourceType = this.getNodeType( builder );
  2263. const sourceSnippet = sourceNode.build( builder );
  2264. const sourceCache = builder.getVarFromNode( this );
  2265. const sourceProperty = builder.getPropertyName( sourceCache );
  2266. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  2267. const length = builder.getTypeLength( sourceType );
  2268. const snippetValues = [];
  2269. let componentIndex = 0;
  2270. for ( let i = 0; i < length; i ++ ) {
  2271. const component = vectorComponents[ i ];
  2272. if ( component === components[ componentIndex ] ) {
  2273. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  2274. componentIndex ++;
  2275. } else {
  2276. snippetValues.push( sourceProperty + '.' + component );
  2277. }
  2278. }
  2279. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  2280. }
  2281. }
  2282. /**
  2283. * Base class for representing data input nodes.
  2284. *
  2285. * @augments Node
  2286. */
  2287. class InputNode extends Node {
  2288. static get type() {
  2289. return 'InputNode';
  2290. }
  2291. /**
  2292. * Constructs a new input node.
  2293. *
  2294. * @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).
  2295. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2296. */
  2297. constructor( value, nodeType = null ) {
  2298. super( nodeType );
  2299. /**
  2300. * This flag can be used for type testing.
  2301. *
  2302. * @type {boolean}
  2303. * @readonly
  2304. * @default true
  2305. */
  2306. this.isInputNode = true;
  2307. /**
  2308. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2309. *
  2310. * @type {any}
  2311. */
  2312. this.value = value;
  2313. /**
  2314. * The precision of the value in the shader.
  2315. *
  2316. * @type {?('low'|'medium'|'high')}
  2317. * @default null
  2318. */
  2319. this.precision = null;
  2320. }
  2321. generateNodeType( /*builder*/ ) {
  2322. if ( this.nodeType === null ) {
  2323. return getValueType( this.value );
  2324. }
  2325. return this.nodeType;
  2326. }
  2327. /**
  2328. * Returns the input type of the node which is by default the node type. Derived modules
  2329. * might overwrite this method and use a fixed type or compute one analytically.
  2330. *
  2331. * A typical example for different input and node types are textures. The input type of a
  2332. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2333. *
  2334. * @param {NodeBuilder} builder - The current node builder.
  2335. * @return {string} The input type.
  2336. */
  2337. getInputType( builder ) {
  2338. return this.getNodeType( builder );
  2339. }
  2340. /**
  2341. * Sets the precision to the given value. The method can be
  2342. * overwritten in derived classes if the final precision must be computed
  2343. * analytically.
  2344. *
  2345. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2346. * @return {InputNode} A reference to this node.
  2347. */
  2348. setPrecision( precision ) {
  2349. this.precision = precision;
  2350. return this;
  2351. }
  2352. serialize( data ) {
  2353. super.serialize( data );
  2354. data.value = this.value;
  2355. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2356. data.valueType = getValueType( this.value );
  2357. data.nodeType = this.nodeType;
  2358. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2359. data.precision = this.precision;
  2360. }
  2361. deserialize( data ) {
  2362. super.deserialize( data );
  2363. this.nodeType = data.nodeType;
  2364. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2365. this.precision = data.precision || null;
  2366. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2367. }
  2368. generate( /*builder, output*/ ) {
  2369. warn( 'Abstract function.' );
  2370. }
  2371. }
  2372. const _regNum = /float|u?int/;
  2373. /**
  2374. * Class for representing a constant value in the shader.
  2375. *
  2376. * @augments InputNode
  2377. */
  2378. class ConstNode extends InputNode {
  2379. static get type() {
  2380. return 'ConstNode';
  2381. }
  2382. /**
  2383. * Constructs a new input node.
  2384. *
  2385. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2386. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2387. */
  2388. constructor( value, nodeType = null ) {
  2389. super( value, nodeType );
  2390. /**
  2391. * This flag can be used for type testing.
  2392. *
  2393. * @type {boolean}
  2394. * @readonly
  2395. * @default true
  2396. */
  2397. this.isConstNode = true;
  2398. }
  2399. /**
  2400. * Generates the shader string of the value with the current node builder.
  2401. *
  2402. * @param {NodeBuilder} builder - The current node builder.
  2403. * @return {string} The generated value as a shader string.
  2404. */
  2405. generateConst( builder ) {
  2406. return builder.generateConst( this.getNodeType( builder ), this.value );
  2407. }
  2408. generate( builder, output ) {
  2409. const type = this.getNodeType( builder );
  2410. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2411. return builder.generateConst( output, this.value );
  2412. }
  2413. return builder.format( this.generateConst( builder ), type, output );
  2414. }
  2415. }
  2416. /**
  2417. * Base class for representing member access on an object-like
  2418. * node data structures.
  2419. *
  2420. * @augments Node
  2421. */
  2422. class MemberNode extends Node {
  2423. static get type() {
  2424. return 'MemberNode';
  2425. }
  2426. /**
  2427. * Constructs a member node.
  2428. *
  2429. * @param {Node} structNode - The struct node.
  2430. * @param {string} property - The property name.
  2431. */
  2432. constructor( structNode, property ) {
  2433. super();
  2434. /**
  2435. * The struct node.
  2436. *
  2437. * @type {Node}
  2438. */
  2439. this.structNode = structNode;
  2440. /**
  2441. * The property name.
  2442. *
  2443. * @type {Node}
  2444. */
  2445. this.property = property;
  2446. /**
  2447. * This flag can be used for type testing.
  2448. *
  2449. * @type {boolean}
  2450. * @readonly
  2451. * @default true
  2452. */
  2453. this.isMemberNode = true;
  2454. }
  2455. hasMember( builder ) {
  2456. if ( this.structNode.isMemberNode ) {
  2457. if ( this.structNode.hasMember( builder ) === false ) {
  2458. return false;
  2459. }
  2460. }
  2461. return this.structNode.getMemberType( builder, this.property ) !== 'void';
  2462. }
  2463. generateNodeType( builder ) {
  2464. if ( this.hasMember( builder ) === false ) {
  2465. // default type if member does not exist
  2466. return 'float';
  2467. }
  2468. return this.structNode.getMemberType( builder, this.property );
  2469. }
  2470. getMemberType( builder, name ) {
  2471. if ( this.hasMember( builder ) === false ) {
  2472. // default type if member does not exist
  2473. return 'float';
  2474. }
  2475. const type = this.getNodeType( builder );
  2476. const struct = builder.getStructTypeNode( type );
  2477. return struct.getMemberType( builder, name );
  2478. }
  2479. generate( builder ) {
  2480. if ( this.hasMember( builder ) === false ) {
  2481. warn( `TSL: Member "${ this.property }" does not exist in struct.`, this.stackTrace );
  2482. const type = this.getNodeType( builder );
  2483. return builder.generateConst( type );
  2484. }
  2485. const propertyName = this.structNode.build( builder );
  2486. return propertyName + '.' + this.property;
  2487. }
  2488. }
  2489. let currentStack = null;
  2490. const NodeElements = new Map();
  2491. // Extend Node Class for TSL using prototype
  2492. function addMethodChaining( name, nodeElement ) {
  2493. // No require StackTrace because this is internal API
  2494. if ( NodeElements.has( name ) ) {
  2495. warn( `TSL: Redefinition of method chaining '${ name }'.` );
  2496. return;
  2497. }
  2498. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2499. NodeElements.set( name, nodeElement );
  2500. if ( name !== 'assign' ) {
  2501. // Changing Node prototype to add method chaining
  2502. Node.prototype[ name ] = function ( ...params ) {
  2503. //if ( name === 'toVarIntent' ) return this;
  2504. return this.isStackNode ? this.addToStack( nodeElement( ...params ) ) : nodeElement( this, ...params );
  2505. };
  2506. // Adding assign method chaining
  2507. Node.prototype[ name + 'Assign' ] = function ( ...params ) {
  2508. return this.isStackNode ? this.assign( params[ 0 ], nodeElement( ...params ) ) : this.assign( nodeElement( this, ...params ) );
  2509. };
  2510. }
  2511. }
  2512. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2513. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2514. Node.prototype.assign = function ( ...params ) {
  2515. if ( this.isStackNode !== true ) {
  2516. if ( currentStack !== null ) {
  2517. currentStack.assign( this, ...params );
  2518. } else {
  2519. error( 'TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().', new StackTrace() );
  2520. }
  2521. return this;
  2522. } else {
  2523. const nodeElement = NodeElements.get( 'assign' );
  2524. return this.addToStack( nodeElement( ...params ) );
  2525. }
  2526. };
  2527. Node.prototype.toVarIntent = function () {
  2528. return this;
  2529. };
  2530. Node.prototype.get = function ( value ) {
  2531. return new MemberNode( this, value );
  2532. };
  2533. // Cache prototype for TSL
  2534. const proto = {};
  2535. // Set swizzle properties for xyzw, rgba, and stpq.
  2536. function setProtoSwizzle( property, altA, altB ) {
  2537. // swizzle properties
  2538. proto[ property ] = proto[ altA ] = proto[ altB ] = {
  2539. get() {
  2540. this._cache = this._cache || {};
  2541. //
  2542. let split = this._cache[ property ];
  2543. if ( split === undefined ) {
  2544. split = new SplitNode( this, property );
  2545. this._cache[ property ] = split;
  2546. }
  2547. return split;
  2548. },
  2549. set( value ) {
  2550. this[ property ].assign( nodeObject( value ) );
  2551. }
  2552. };
  2553. // set properties ( swizzle ) and sort to xyzw sequence
  2554. const propUpper = property.toUpperCase();
  2555. const altAUpper = altA.toUpperCase();
  2556. const altBUpper = altB.toUpperCase();
  2557. // Set methods for swizzle properties
  2558. Node.prototype[ 'set' + propUpper ] = Node.prototype[ 'set' + altAUpper ] = Node.prototype[ 'set' + altBUpper ] = function ( value ) {
  2559. const swizzle = parseSwizzleAndSort( property );
  2560. return new SetNode( this, swizzle, nodeObject( value ) );
  2561. };
  2562. // Set methods for flip properties
  2563. Node.prototype[ 'flip' + propUpper ] = Node.prototype[ 'flip' + altAUpper ] = Node.prototype[ 'flip' + altBUpper ] = function () {
  2564. const swizzle = parseSwizzleAndSort( property );
  2565. return new FlipNode( this, swizzle );
  2566. };
  2567. }
  2568. const swizzleA = [ 'x', 'y', 'z', 'w' ];
  2569. const swizzleB = [ 'r', 'g', 'b', 'a' ];
  2570. const swizzleC = [ 's', 't', 'p', 'q' ];
  2571. for ( let a = 0; a < 4; a ++ ) {
  2572. let prop = swizzleA[ a ];
  2573. let altA = swizzleB[ a ];
  2574. let altB = swizzleC[ a ];
  2575. setProtoSwizzle( prop, altA, altB );
  2576. for ( let b = 0; b < 4; b ++ ) {
  2577. prop = swizzleA[ a ] + swizzleA[ b ];
  2578. altA = swizzleB[ a ] + swizzleB[ b ];
  2579. altB = swizzleC[ a ] + swizzleC[ b ];
  2580. setProtoSwizzle( prop, altA, altB );
  2581. for ( let c = 0; c < 4; c ++ ) {
  2582. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ];
  2583. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ];
  2584. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ];
  2585. setProtoSwizzle( prop, altA, altB );
  2586. for ( let d = 0; d < 4; d ++ ) {
  2587. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ] + swizzleA[ d ];
  2588. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ] + swizzleB[ d ];
  2589. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ] + swizzleC[ d ];
  2590. setProtoSwizzle( prop, altA, altB );
  2591. }
  2592. }
  2593. }
  2594. }
  2595. // Set/get static properties for array elements (0-31).
  2596. for ( let i = 0; i < 32; i ++ ) {
  2597. proto[ i ] = {
  2598. get() {
  2599. this._cache = this._cache || {};
  2600. //
  2601. let element = this._cache[ i ];
  2602. if ( element === undefined ) {
  2603. element = new ArrayElementNode( this, new ConstNode( i, 'uint' ) );
  2604. this._cache[ i ] = element;
  2605. }
  2606. return element;
  2607. },
  2608. set( value ) {
  2609. this[ i ].assign( nodeObject( value ) );
  2610. }
  2611. };
  2612. }
  2613. /*
  2614. // Set properties for width, height, and depth.
  2615. function setProtoProperty( property, target ) {
  2616. proto[ property ] = {
  2617. get() {
  2618. this._cache = this._cache || {};
  2619. //
  2620. let split = this._cache[ target ];
  2621. if ( split === undefined ) {
  2622. split = new SplitNode( this, target );
  2623. this._cache[ target ] = split;
  2624. }
  2625. return split;
  2626. },
  2627. set( value ) {
  2628. this[ target ].assign( nodeObject( value ) );
  2629. }
  2630. };
  2631. }
  2632. setProtoProperty( 'width', 'x' );
  2633. setProtoProperty( 'height', 'y' );
  2634. setProtoProperty( 'depth', 'z' );
  2635. */
  2636. Object.defineProperties( Node.prototype, proto );
  2637. // --- FINISH ---
  2638. const ShaderNodeObject = function ( obj, altType = null ) {
  2639. const type = getValueType( obj );
  2640. if ( type === 'node' ) {
  2641. return obj;
  2642. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2643. return nodeObject( getConstNode( obj, altType ) );
  2644. } else if ( type === 'shader' ) {
  2645. return obj.isFn ? obj : Fn( obj );
  2646. }
  2647. return obj;
  2648. };
  2649. const ShaderNodeObjects = function ( objects, altType = null ) {
  2650. for ( const name in objects ) {
  2651. objects[ name ] = nodeObject( objects[ name ], altType );
  2652. }
  2653. return objects;
  2654. };
  2655. const ShaderNodeArray = function ( array, altType = null ) {
  2656. const len = array.length;
  2657. for ( let i = 0; i < len; i ++ ) {
  2658. array[ i ] = nodeObject( array[ i ], altType );
  2659. }
  2660. return array;
  2661. };
  2662. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2663. function assignNode( node ) {
  2664. if ( settings !== null ) {
  2665. node = nodeObject( Object.assign( node, settings ) );
  2666. if ( settings.intent === true ) {
  2667. node = node.toVarIntent();
  2668. }
  2669. } else {
  2670. node = nodeObject( node );
  2671. }
  2672. return node;
  2673. }
  2674. let fn, name = scope, minParams, maxParams;
  2675. function verifyParamsLimit( params ) {
  2676. let tslName;
  2677. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2678. else tslName = NodeClass.type;
  2679. if ( minParams !== undefined && params.length < minParams ) {
  2680. error( `TSL: "${ tslName }" parameter length is less than minimum required.`, new StackTrace() );
  2681. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2682. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2683. error( `TSL: "${ tslName }" parameter length exceeds limit.`, new StackTrace() );
  2684. return params.slice( 0, maxParams );
  2685. }
  2686. return params;
  2687. }
  2688. if ( scope === null ) {
  2689. fn = ( ...params ) => {
  2690. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2691. };
  2692. } else if ( factor !== null ) {
  2693. factor = nodeObject( factor );
  2694. fn = ( ...params ) => {
  2695. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2696. };
  2697. } else {
  2698. fn = ( ...params ) => {
  2699. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2700. };
  2701. }
  2702. fn.setParameterLength = ( ...params ) => {
  2703. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2704. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2705. return fn;
  2706. };
  2707. fn.setName = ( value ) => {
  2708. name = value;
  2709. return fn;
  2710. };
  2711. return fn;
  2712. };
  2713. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2714. return new NodeClass( ...nodeArray( params ) );
  2715. };
  2716. class ShaderCallNodeInternal extends Node {
  2717. constructor( shaderNode, rawInputs ) {
  2718. super();
  2719. this.shaderNode = shaderNode;
  2720. this.rawInputs = rawInputs;
  2721. this.isShaderCallNodeInternal = true;
  2722. }
  2723. generateNodeType( builder ) {
  2724. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2725. }
  2726. getElementType( builder ) {
  2727. return this.getOutputNode( builder ).getElementType( builder );
  2728. }
  2729. getMemberType( builder, name ) {
  2730. return this.getOutputNode( builder ).getMemberType( builder, name );
  2731. }
  2732. call( builder ) {
  2733. const { shaderNode, rawInputs } = this;
  2734. const properties = builder.getNodeProperties( shaderNode );
  2735. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2736. const subBuildProperty = subBuild || 'default';
  2737. if ( properties[ subBuildProperty ] ) {
  2738. return properties[ subBuildProperty ];
  2739. }
  2740. //
  2741. const previousSubBuildFn = builder.subBuildFn;
  2742. const previousFnCall = builder.fnCall;
  2743. builder.subBuildFn = subBuild;
  2744. builder.fnCall = this;
  2745. let result = null;
  2746. if ( shaderNode.layout ) {
  2747. // build inputs first
  2748. if ( rawInputs ) {
  2749. // use layout inputs to ensure that no extra parameters are built
  2750. const inputs = shaderNode.layout.inputs;
  2751. if ( isArrayAsParameter( rawInputs ) ) {
  2752. const rawArrayParameters = rawInputs;
  2753. for ( let i = 0; i < inputs.length; i ++ ) {
  2754. const rawParameter = rawArrayParameters[ i ];
  2755. if ( rawParameter && rawParameter.isNode ) {
  2756. rawParameter.build( builder );
  2757. }
  2758. }
  2759. } else {
  2760. const rawObjectParameters = rawInputs[ 0 ];
  2761. for ( const param of inputs ) {
  2762. const rawParameter = rawObjectParameters[ param.name ];
  2763. if ( rawParameter && rawParameter.isNode ) {
  2764. rawParameter.build( builder );
  2765. }
  2766. }
  2767. }
  2768. }
  2769. const functionNode = builder.buildFunctionNode( shaderNode );
  2770. builder.addInclude( functionNode );
  2771. //
  2772. const inputs = rawInputs ? getLayoutParameters( rawInputs ) : null;
  2773. result = functionNode.call( inputs );
  2774. } else {
  2775. const secureNodeBuilder = new Proxy( builder, {
  2776. get: ( target, property, receiver ) => {
  2777. let value;
  2778. if ( Symbol.iterator === property ) {
  2779. value = function* () {
  2780. yield undefined;
  2781. };
  2782. } else {
  2783. value = Reflect.get( target, property, receiver );
  2784. }
  2785. return value;
  2786. }
  2787. } );
  2788. //
  2789. const inputs = rawInputs ? getProxyParameters( rawInputs ) : null;
  2790. const hasParameters = Array.isArray( rawInputs ) ? rawInputs.length > 0 : rawInputs !== null;
  2791. const jsFunc = shaderNode.jsFunc;
  2792. const outputNode = hasParameters || jsFunc.length > 1 ? jsFunc( inputs, secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2793. result = nodeObject( outputNode );
  2794. }
  2795. builder.subBuildFn = previousSubBuildFn;
  2796. builder.fnCall = previousFnCall;
  2797. if ( shaderNode.once ) {
  2798. properties[ subBuildProperty ] = result;
  2799. }
  2800. return result;
  2801. }
  2802. setupOutput( builder ) {
  2803. builder.addStack();
  2804. builder.stack.outputNode = this.call( builder );
  2805. return builder.removeStack();
  2806. }
  2807. getOutputNode( builder ) {
  2808. const properties = builder.getNodeProperties( this );
  2809. const subBuildOutput = builder.getSubBuildOutput( this );
  2810. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2811. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2812. return properties[ subBuildOutput ];
  2813. }
  2814. build( builder, output = null ) {
  2815. let result = null;
  2816. const buildStage = builder.getBuildStage();
  2817. const properties = builder.getNodeProperties( this );
  2818. const subBuildOutput = builder.getSubBuildOutput( this );
  2819. const outputNode = this.getOutputNode( builder );
  2820. const previousFnCall = builder.fnCall;
  2821. builder.fnCall = this;
  2822. if ( buildStage === 'setup' ) {
  2823. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2824. if ( properties[ subBuildInitialized ] !== true ) {
  2825. properties[ subBuildInitialized ] = true;
  2826. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2827. properties[ subBuildOutput ].build( builder );
  2828. // If the shaderNode has subBuilds, add them to the chaining nodes
  2829. // so they can be built later in the build process.
  2830. if ( this.shaderNode.subBuilds ) {
  2831. for ( const node of builder.chaining ) {
  2832. const nodeData = builder.getDataFromNode( node, 'any' );
  2833. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2834. for ( const subBuild of this.shaderNode.subBuilds ) {
  2835. nodeData.subBuilds.add( subBuild );
  2836. }
  2837. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2838. }
  2839. }
  2840. }
  2841. result = properties[ subBuildOutput ];
  2842. } else if ( buildStage === 'analyze' ) {
  2843. outputNode.build( builder, output );
  2844. } else if ( buildStage === 'generate' ) {
  2845. result = outputNode.build( builder, output ) || '';
  2846. }
  2847. builder.fnCall = previousFnCall;
  2848. return result;
  2849. }
  2850. }
  2851. function isArrayAsParameter( params ) {
  2852. return params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2853. }
  2854. function getLayoutParameters( params ) {
  2855. let output;
  2856. nodeObjects( params );
  2857. if ( isArrayAsParameter( params ) ) {
  2858. output = [ ...params ];
  2859. } else {
  2860. output = params[ 0 ];
  2861. }
  2862. return output;
  2863. }
  2864. function getProxyParameters( params ) {
  2865. let index = 0;
  2866. nodeObjects( params );
  2867. return new Proxy( params, {
  2868. get: ( target, property, receiver ) => {
  2869. let value;
  2870. if ( property === 'length' ) {
  2871. value = params.length;
  2872. return value;
  2873. }
  2874. if ( Symbol.iterator === property ) {
  2875. value = function* () {
  2876. for ( const inputNode of params ) {
  2877. yield nodeObject( inputNode );
  2878. }
  2879. };
  2880. } else {
  2881. if ( params.length > 0 ) {
  2882. if ( Object.getPrototypeOf( params[ 0 ] ) === Object.prototype ) {
  2883. const objectTarget = params[ 0 ];
  2884. if ( objectTarget[ property ] === undefined ) {
  2885. value = objectTarget[ index ++ ];
  2886. } else {
  2887. value = Reflect.get( objectTarget, property, receiver );
  2888. }
  2889. } else if ( params[ 0 ] instanceof Node ) {
  2890. if ( params[ property ] === undefined ) {
  2891. value = params[ index ++ ];
  2892. } else {
  2893. value = Reflect.get( params, property, receiver );
  2894. }
  2895. }
  2896. } else {
  2897. value = Reflect.get( target, property, receiver );
  2898. }
  2899. value = nodeObject( value );
  2900. }
  2901. return value;
  2902. }
  2903. } );
  2904. }
  2905. class ShaderNodeInternal extends Node {
  2906. constructor( jsFunc, nodeType ) {
  2907. super( nodeType );
  2908. this.jsFunc = jsFunc;
  2909. this.layout = null;
  2910. this.global = true;
  2911. this.once = false;
  2912. }
  2913. setLayout( layout ) {
  2914. this.layout = layout;
  2915. return this;
  2916. }
  2917. getLayout() {
  2918. return this.layout;
  2919. }
  2920. call( rawInputs = null ) {
  2921. return new ShaderCallNodeInternal( this, rawInputs );
  2922. }
  2923. setup() {
  2924. return this.call();
  2925. }
  2926. }
  2927. const bools = [ false, true ];
  2928. const uints = [ 0, 1, 2, 3 ];
  2929. const ints = [ -1, -2 ];
  2930. 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 ];
  2931. const boolsCacheMap = new Map();
  2932. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2933. const uintsCacheMap = new Map();
  2934. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2935. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2936. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2937. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2938. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2939. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2940. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2941. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2942. const getConstNode = ( value, type ) => {
  2943. if ( constNodesCacheMap.has( value ) ) {
  2944. return constNodesCacheMap.get( value );
  2945. } else if ( value.isNode === true ) {
  2946. return value;
  2947. } else {
  2948. return new ConstNode( value, type );
  2949. }
  2950. };
  2951. const ConvertType = function ( type, cacheMap = null ) {
  2952. return ( ...params ) => {
  2953. for ( const param of params ) {
  2954. if ( param === undefined ) {
  2955. error( `TSL: Invalid parameter for the type "${ type }".`, new StackTrace() );
  2956. return new ConstNode( 0, type );
  2957. }
  2958. }
  2959. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2960. const paramType = typeof param;
  2961. return paramType !== 'object' && paramType !== 'function';
  2962. } ) ) ) {
  2963. params = [ getValueFromType( type, ...params ) ];
  2964. }
  2965. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2966. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2967. }
  2968. if ( params.length === 1 ) {
  2969. const node = getConstNode( params[ 0 ], type );
  2970. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2971. return nodeObjectIntent( new ConvertNode( node, type ) );
  2972. }
  2973. const nodes = params.map( param => getConstNode( param ) );
  2974. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2975. };
  2976. };
  2977. // exports
  2978. function defined( value ) {
  2979. if ( value && value.isNode ) {
  2980. value.traverse( ( node ) => {
  2981. if ( node.isConstNode ) {
  2982. value = node.value;
  2983. }
  2984. } );
  2985. }
  2986. return Boolean( value );
  2987. }
  2988. // utils
  2989. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2990. // shader node base
  2991. function ShaderNode( jsFunc, nodeType ) {
  2992. return new ShaderNodeInternal( jsFunc, nodeType );
  2993. }
  2994. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2995. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2996. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2997. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2998. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2999. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  3000. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { ...settings, intent: true } );
  3001. const nodeProxyConstructor = ( constructorFunction, nodeInstance ) => {
  3002. return new Proxy( constructorFunction, {
  3003. get( target, prop, receiver ) {
  3004. return Reflect.get( nodeInstance, prop, receiver );
  3005. },
  3006. set( target, prop, value ) {
  3007. return Reflect.set( nodeInstance, prop, value );
  3008. }
  3009. } );
  3010. };
  3011. let fnId = 0;
  3012. class FnNode extends Node {
  3013. constructor( jsFunc, layout = null ) {
  3014. super();
  3015. let nodeType = null;
  3016. if ( layout !== null ) {
  3017. if ( typeof layout === 'object' ) {
  3018. nodeType = layout.return;
  3019. } else {
  3020. if ( typeof layout === 'string' ) {
  3021. nodeType = layout;
  3022. } else {
  3023. error( 'TSL: Invalid layout type.', new StackTrace() );
  3024. }
  3025. layout = null;
  3026. }
  3027. }
  3028. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  3029. if ( layout !== null ) {
  3030. this.setLayout( layout );
  3031. }
  3032. this.isFn = true;
  3033. }
  3034. setLayout( layout ) {
  3035. const nodeType = this.shaderNode.nodeType;
  3036. if ( typeof layout.inputs !== 'object' ) {
  3037. const fullLayout = {
  3038. name: 'fn' + fnId ++,
  3039. type: nodeType,
  3040. inputs: []
  3041. };
  3042. for ( const name in layout ) {
  3043. if ( name === 'return' ) continue;
  3044. fullLayout.inputs.push( {
  3045. name: name,
  3046. type: layout[ name ]
  3047. } );
  3048. }
  3049. layout = fullLayout;
  3050. }
  3051. this.shaderNode.setLayout( layout );
  3052. return this;
  3053. }
  3054. generateNodeType( builder ) {
  3055. return this.shaderNode.getNodeType( builder ) || 'float';
  3056. }
  3057. call( ...params ) {
  3058. const fnCall = this.shaderNode.call( params );
  3059. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  3060. return fnCall.toVarIntent();
  3061. }
  3062. once( subBuilds = null ) {
  3063. this.shaderNode.once = true;
  3064. this.shaderNode.subBuilds = subBuilds;
  3065. return this;
  3066. }
  3067. generate( builder ) {
  3068. const type = this.getNodeType( builder );
  3069. error( 'TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".', this.stackTrace );
  3070. return builder.generateConst( type );
  3071. }
  3072. }
  3073. function Fn( jsFunc, layout = null ) {
  3074. const instance = new FnNode( jsFunc, layout );
  3075. return new Proxy( () => {}, {
  3076. apply( target, thisArg, params ) {
  3077. return instance.call( ...params );
  3078. },
  3079. get( target, prop, receiver ) {
  3080. return Reflect.get( instance, prop, receiver );
  3081. },
  3082. set( target, prop, value, receiver ) {
  3083. return Reflect.set( instance, prop, value, receiver );
  3084. }
  3085. } );
  3086. }
  3087. //
  3088. const setCurrentStack = ( stack ) => {
  3089. currentStack = stack;
  3090. };
  3091. const getCurrentStack = () => currentStack;
  3092. /**
  3093. * Represent a conditional node using if/else statements.
  3094. *
  3095. * ```js
  3096. * If( condition, function )
  3097. * .ElseIf( condition, function )
  3098. * .Else( function )
  3099. * ```
  3100. * @tsl
  3101. * @function
  3102. * @param {...any} params - The parameters for the conditional node.
  3103. * @returns {StackNode} The conditional node.
  3104. */
  3105. const If = ( ...params ) => currentStack.If( ...params );
  3106. /**
  3107. * Represent a conditional node using switch/case statements.
  3108. *
  3109. * ```js
  3110. * Switch( value )
  3111. * .Case( 1, function )
  3112. * .Case( 2, 3, 4, function )
  3113. * .Default( function )
  3114. * ```
  3115. * @tsl
  3116. * @function
  3117. * @param {...any} params - The parameters for the conditional node.
  3118. * @returns {StackNode} The conditional node.
  3119. */
  3120. const Switch = ( ...params ) => currentStack.Switch( ...params );
  3121. /**
  3122. * Add the given node to the current stack.
  3123. *
  3124. * @param {Node} node - The node to add.
  3125. * @returns {Node} The node that was added to the stack.
  3126. */
  3127. function Stack( node ) {
  3128. if ( currentStack ) currentStack.addToStack( node );
  3129. return node;
  3130. }
  3131. addMethodChaining( 'toStack', Stack );
  3132. // types
  3133. const color = new ConvertType( 'color' );
  3134. const float = new ConvertType( 'float', cacheMaps.float );
  3135. const int = new ConvertType( 'int', cacheMaps.ints );
  3136. const uint = new ConvertType( 'uint', cacheMaps.uint );
  3137. const bool = new ConvertType( 'bool', cacheMaps.bool );
  3138. const vec2 = new ConvertType( 'vec2' );
  3139. const ivec2 = new ConvertType( 'ivec2' );
  3140. const uvec2 = new ConvertType( 'uvec2' );
  3141. const bvec2 = new ConvertType( 'bvec2' );
  3142. const vec3 = new ConvertType( 'vec3' );
  3143. const ivec3 = new ConvertType( 'ivec3' );
  3144. const uvec3 = new ConvertType( 'uvec3' );
  3145. const bvec3 = new ConvertType( 'bvec3' );
  3146. const vec4 = new ConvertType( 'vec4' );
  3147. const ivec4 = new ConvertType( 'ivec4' );
  3148. const uvec4 = new ConvertType( 'uvec4' );
  3149. const bvec4 = new ConvertType( 'bvec4' );
  3150. const mat2 = new ConvertType( 'mat2' );
  3151. const mat3 = new ConvertType( 'mat3' );
  3152. const mat4 = new ConvertType( 'mat4' );
  3153. addMethodChaining( 'toColor', color );
  3154. addMethodChaining( 'toFloat', float );
  3155. addMethodChaining( 'toInt', int );
  3156. addMethodChaining( 'toUint', uint );
  3157. addMethodChaining( 'toBool', bool );
  3158. addMethodChaining( 'toVec2', vec2 );
  3159. addMethodChaining( 'toIVec2', ivec2 );
  3160. addMethodChaining( 'toUVec2', uvec2 );
  3161. addMethodChaining( 'toBVec2', bvec2 );
  3162. addMethodChaining( 'toVec3', vec3 );
  3163. addMethodChaining( 'toIVec3', ivec3 );
  3164. addMethodChaining( 'toUVec3', uvec3 );
  3165. addMethodChaining( 'toBVec3', bvec3 );
  3166. addMethodChaining( 'toVec4', vec4 );
  3167. addMethodChaining( 'toIVec4', ivec4 );
  3168. addMethodChaining( 'toUVec4', uvec4 );
  3169. addMethodChaining( 'toBVec4', bvec4 );
  3170. addMethodChaining( 'toMat2', mat2 );
  3171. addMethodChaining( 'toMat3', mat3 );
  3172. addMethodChaining( 'toMat4', mat4 );
  3173. // basic nodes
  3174. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  3175. const convert = ( node, types ) => new ConvertNode( nodeObject( node ), types );
  3176. const split = ( node, channels ) => new SplitNode( nodeObject( node ), channels );
  3177. addMethodChaining( 'element', element );
  3178. addMethodChaining( 'convert', convert );
  3179. // deprecated
  3180. /**
  3181. * @tsl
  3182. * @function
  3183. * @deprecated since r176. Use {@link Stack} instead.
  3184. *
  3185. * @param {Node} node - The node to add.
  3186. * @returns {Function}
  3187. */
  3188. const append = ( node ) => { // @deprecated, r176
  3189. warn( 'TSL: append() has been renamed to Stack().', new StackTrace() );
  3190. return Stack( node );
  3191. };
  3192. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  3193. warn( 'TSL: .append() has been renamed to .toStack().', new StackTrace() );
  3194. return Stack( node );
  3195. } );
  3196. /**
  3197. * This class represents a shader property. It can be used
  3198. * to explicitly define a property and assign a value to it.
  3199. *
  3200. * ```js
  3201. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  3202. *```
  3203. * `PropertyNode` is used by the engine to predefined common material properties
  3204. * for TSL code.
  3205. *
  3206. * @augments Node
  3207. */
  3208. class PropertyNode extends Node {
  3209. static get type() {
  3210. return 'PropertyNode';
  3211. }
  3212. /**
  3213. * Constructs a new property node.
  3214. *
  3215. * @param {string} nodeType - The type of the node.
  3216. * @param {?string} [name=null] - The name of the property in the shader.
  3217. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  3218. * @param {?Node} [placeholderNode=null] - The placeholder node if not assigned.
  3219. */
  3220. constructor( nodeType, name = null, varying = false, placeholderNode = null ) {
  3221. super( nodeType );
  3222. /**
  3223. * The name of the property in the shader. If no name is defined,
  3224. * the node system auto-generates one.
  3225. *
  3226. * @type {?string}
  3227. * @default null
  3228. */
  3229. this.name = name;
  3230. /**
  3231. * Whether this property is a varying or not.
  3232. *
  3233. * @type {boolean}
  3234. * @default false
  3235. */
  3236. this.varying = varying;
  3237. /**
  3238. * The placeholder node of the property if it is not assigned.
  3239. *
  3240. * @type {?Node}
  3241. * @default null
  3242. */
  3243. this.placeholderNode = nodeObject( placeholderNode );
  3244. /**
  3245. * This flag can be used for type testing.
  3246. *
  3247. * @type {boolean}
  3248. * @readonly
  3249. * @default true
  3250. */
  3251. this.isPropertyNode = true;
  3252. /**
  3253. * This flag is used for global cache.
  3254. *
  3255. * @type {boolean}
  3256. * @default true
  3257. */
  3258. this.global = true;
  3259. }
  3260. getNodeType( builder ) {
  3261. const nodeType = super.getNodeType( builder );
  3262. if ( nodeType === 'output' ) {
  3263. return builder.getOutputType();
  3264. }
  3265. return nodeType;
  3266. }
  3267. customCacheKey() {
  3268. return hashString( this.type + ':' + ( this.name || '' ) + ':' + ( this.varying ? '1' : '0' ) );
  3269. }
  3270. getHash( builder ) {
  3271. return this.name || super.getHash( builder );
  3272. }
  3273. generate( builder ) {
  3274. let nodeVar;
  3275. if ( this.varying === true ) {
  3276. nodeVar = builder.getVaryingFromNode( this, this.name );
  3277. nodeVar.needsInterpolation = true;
  3278. } else {
  3279. nodeVar = builder.getVarFromNode( this, this.name );
  3280. if ( this.placeholderNode !== null ) {
  3281. if ( builder.hasWriteUsage( this ) === false ) {
  3282. const snippet = this.placeholderNode.build( builder, this.getNodeType( builder ) );
  3283. builder.addLineFlowCode( `${ builder.getPropertyName( nodeVar ) } = ${ snippet }`, this );
  3284. }
  3285. }
  3286. }
  3287. return builder.getPropertyName( nodeVar );
  3288. }
  3289. }
  3290. /**
  3291. * TSL function for creating a property node.
  3292. *
  3293. * @tsl
  3294. * @function
  3295. * @param {string} type - The type of the node.
  3296. * @param {?string} [name=null] - The name of the property in the shader.
  3297. * @param {?Node} [placeholderNode=null] - The placeholder node if not assigned.
  3298. * @returns {PropertyNode}
  3299. */
  3300. const property = ( type, name, placeholderNode = null ) => new PropertyNode( type, name, false, placeholderNode );
  3301. /**
  3302. * TSL function for creating a varying property node.
  3303. *
  3304. * @tsl
  3305. * @function
  3306. * @param {string} type - The type of the node.
  3307. * @param {?string} [name=null] - The name of the varying in the shader.
  3308. * @param {?Node} [placeholderNode=null] - The placeholder node if not assigned.
  3309. * @returns {PropertyNode}
  3310. */
  3311. const varyingProperty = ( type, name, placeholderNode = null ) => new PropertyNode( type, name, true, placeholderNode );
  3312. /**
  3313. * TSL object that represents the shader variable `DiffuseColor`.
  3314. *
  3315. * @tsl
  3316. * @type {PropertyNode<vec4>}
  3317. */
  3318. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  3319. /**
  3320. * TSL object that represents the shader variable `DiffuseContribution`.
  3321. *
  3322. * @tsl
  3323. * @type {PropertyNode<vec3>}
  3324. */
  3325. const diffuseContribution = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'DiffuseContribution' );
  3326. /**
  3327. * TSL object that represents the shader variable `EmissiveColor`.
  3328. *
  3329. * @tsl
  3330. * @type {PropertyNode<vec3>}
  3331. */
  3332. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  3333. /**
  3334. * TSL object that represents the shader variable `Roughness`.
  3335. *
  3336. * @tsl
  3337. * @type {PropertyNode<float>}
  3338. */
  3339. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  3340. /**
  3341. * TSL object that represents the shader variable `Metalness`.
  3342. *
  3343. * @tsl
  3344. * @type {PropertyNode<float>}
  3345. */
  3346. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  3347. /**
  3348. * TSL object that represents the shader variable `Clearcoat`.
  3349. *
  3350. * @tsl
  3351. * @type {PropertyNode<float>}
  3352. */
  3353. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  3354. /**
  3355. * TSL object that represents the shader variable `ClearcoatRoughness`.
  3356. *
  3357. * @tsl
  3358. * @type {PropertyNode<float>}
  3359. */
  3360. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  3361. /**
  3362. * TSL object that represents the shader variable `Sheen`.
  3363. *
  3364. * @tsl
  3365. * @type {PropertyNode<vec3>}
  3366. */
  3367. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  3368. /**
  3369. * TSL object that represents the shader variable `SheenRoughness`.
  3370. *
  3371. * @tsl
  3372. * @type {PropertyNode<float>}
  3373. */
  3374. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  3375. /**
  3376. * TSL object that represents the shader variable `Iridescence`.
  3377. *
  3378. * @tsl
  3379. * @type {PropertyNode<float>}
  3380. */
  3381. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  3382. /**
  3383. * TSL object that represents the shader variable `IridescenceIOR`.
  3384. *
  3385. * @tsl
  3386. * @type {PropertyNode<float>}
  3387. */
  3388. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  3389. /**
  3390. * TSL object that represents the shader variable `IridescenceThickness`.
  3391. *
  3392. * @tsl
  3393. * @type {PropertyNode<float>}
  3394. */
  3395. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  3396. /**
  3397. * TSL object that represents the shader variable `AlphaT`.
  3398. *
  3399. * @tsl
  3400. * @type {PropertyNode<float>}
  3401. */
  3402. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  3403. /**
  3404. * TSL object that represents the shader variable `Anisotropy`.
  3405. *
  3406. * @tsl
  3407. * @type {PropertyNode<float>}
  3408. */
  3409. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  3410. /**
  3411. * TSL object that represents the shader variable `AnisotropyT`.
  3412. *
  3413. * @tsl
  3414. * @type {PropertyNode<vec3>}
  3415. */
  3416. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  3417. /**
  3418. * TSL object that represents the shader variable `AnisotropyB`.
  3419. *
  3420. * @tsl
  3421. * @type {PropertyNode<vec3>}
  3422. */
  3423. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  3424. /**
  3425. * TSL object that represents the shader variable `SpecularColor`.
  3426. *
  3427. * @tsl
  3428. * @type {PropertyNode<color>}
  3429. */
  3430. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  3431. /**
  3432. * TSL object that represents the shader variable `SpecularColorBlended`.
  3433. *
  3434. * @tsl
  3435. * @type {PropertyNode<color>}
  3436. */
  3437. const specularColorBlended = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColorBlended' );
  3438. /**
  3439. * TSL object that represents the shader variable `SpecularF90`.
  3440. *
  3441. * @tsl
  3442. * @type {PropertyNode<float>}
  3443. */
  3444. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  3445. /**
  3446. * TSL object that represents the shader variable `Shininess`.
  3447. *
  3448. * @tsl
  3449. * @type {PropertyNode<float>}
  3450. */
  3451. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  3452. /**
  3453. * TSL object that represents the shader variable `Output`.
  3454. *
  3455. * @tsl
  3456. * @type {PropertyNode<vec4>}
  3457. */
  3458. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'output', 'Output' );
  3459. /**
  3460. * TSL object that represents the shader variable `dashSize`.
  3461. *
  3462. * @tsl
  3463. * @type {PropertyNode<float>}
  3464. */
  3465. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  3466. /**
  3467. * TSL object that represents the shader variable `gapSize`.
  3468. *
  3469. * @tsl
  3470. * @type {PropertyNode<float>}
  3471. */
  3472. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  3473. /**
  3474. * TSL object that represents the shader variable `pointWidth`.
  3475. *
  3476. * @tsl
  3477. * @type {PropertyNode<float>}
  3478. */
  3479. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  3480. /**
  3481. * TSL object that represents the shader variable `IOR`.
  3482. *
  3483. * @tsl
  3484. * @type {PropertyNode<float>}
  3485. */
  3486. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  3487. /**
  3488. * TSL object that represents the shader variable `Transmission`.
  3489. *
  3490. * @tsl
  3491. * @type {PropertyNode<float>}
  3492. */
  3493. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  3494. /**
  3495. * TSL object that represents the shader variable `Thickness`.
  3496. *
  3497. * @tsl
  3498. * @type {PropertyNode<float>}
  3499. */
  3500. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  3501. /**
  3502. * TSL object that represents the shader variable `AttenuationDistance`.
  3503. *
  3504. * @tsl
  3505. * @type {PropertyNode<float>}
  3506. */
  3507. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  3508. /**
  3509. * TSL object that represents the shader variable `AttenuationColor`.
  3510. *
  3511. * @tsl
  3512. * @type {PropertyNode<color>}
  3513. */
  3514. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3515. /**
  3516. * TSL object that represents the shader variable `Dispersion`.
  3517. *
  3518. * @tsl
  3519. * @type {PropertyNode<float>}
  3520. */
  3521. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3522. /**
  3523. * TSL object that represents the shader variable `AmbientOcclusion`.
  3524. * If no value is assigned to this property, it defaults to a placeholder value of `1.0`.
  3525. *
  3526. * @tsl
  3527. * @type {PropertyNode<float>}
  3528. */
  3529. const ambientOcclusion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AmbientOcclusion', false, 1 );
  3530. /**
  3531. * This node can be used to group single instances of {@link UniformNode}
  3532. * and manage them as a uniform buffer.
  3533. *
  3534. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3535. * will be used when defining the {@link UniformNode#groupNode} property.
  3536. *
  3537. * - `objectGroup`: Uniform buffer per object.
  3538. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3539. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3540. *
  3541. * @augments Node
  3542. */
  3543. class UniformGroupNode extends Node {
  3544. static get type() {
  3545. return 'UniformGroupNode';
  3546. }
  3547. /**
  3548. * Constructs a new uniform group node.
  3549. *
  3550. * @param {string} name - The name of the uniform group node.
  3551. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3552. * @param {number} [order=1] - Influences the internal sorting.
  3553. * @param {string|null} [updateType=null] - The update type of the uniform group node.
  3554. */
  3555. constructor( name, shared = false, order = 1, updateType = null ) {
  3556. super( 'string' );
  3557. /**
  3558. * The name of the uniform group node.
  3559. *
  3560. * @type {string}
  3561. */
  3562. this.name = name;
  3563. /**
  3564. * Whether this uniform group node is shared or not.
  3565. *
  3566. * @type {boolean}
  3567. * @default false
  3568. */
  3569. this.shared = shared;
  3570. /**
  3571. * Influences the internal sorting.
  3572. * TODO: Add details when this property should be changed.
  3573. *
  3574. * @type {number}
  3575. * @default 1
  3576. */
  3577. this.order = order;
  3578. /**
  3579. * The update type of the uniform group node.
  3580. *
  3581. * @type {string|null}
  3582. * @default null
  3583. */
  3584. this.updateType = updateType;
  3585. /**
  3586. * This flag can be used for type testing.
  3587. *
  3588. * @type {boolean}
  3589. * @readonly
  3590. * @default true
  3591. */
  3592. this.isUniformGroup = true;
  3593. }
  3594. /**
  3595. * Marks the uniform group node as needing an update.
  3596. * This will trigger the necessary updates in the rendering process.
  3597. */
  3598. update() {
  3599. this.needsUpdate = true;
  3600. }
  3601. /**
  3602. * Serializes the uniform group node to a JSON object.
  3603. *
  3604. * @param {Object} data - The object to store the serialized data.
  3605. */
  3606. serialize( data ) {
  3607. super.serialize( data );
  3608. data.name = this.name;
  3609. data.version = this.version;
  3610. data.shared = this.shared;
  3611. }
  3612. /**
  3613. * Deserializes the uniform group node from a JSON object.
  3614. *
  3615. * @param {Object} data - The object containing the serialized data.
  3616. */
  3617. deserialize( data ) {
  3618. super.deserialize( data );
  3619. this.name = data.name;
  3620. this.version = data.version;
  3621. this.shared = data.shared;
  3622. }
  3623. }
  3624. /**
  3625. * TSL function for creating a uniform group node with the given name.
  3626. *
  3627. * @tsl
  3628. * @function
  3629. * @param {string} name - The name of the uniform group node.
  3630. * @returns {UniformGroupNode}
  3631. */
  3632. const uniformGroup = ( name, order = 1, updateType = null ) => new UniformGroupNode( name, false, order, updateType );
  3633. /**
  3634. * TSL function for creating a shared uniform group node with the given name and order.
  3635. *
  3636. * @tsl
  3637. * @function
  3638. * @param {string} name - The name of the uniform group node.
  3639. * @param {number} [order=0] - Influences the internal sorting.
  3640. * @returns {UniformGroupNode}
  3641. */
  3642. const sharedUniformGroup = ( name, order = 0, updateType = null ) => new UniformGroupNode( name, true, order, updateType );
  3643. /**
  3644. * TSL object that represents a shared uniform group node which is updated once per frame.
  3645. *
  3646. * @tsl
  3647. * @type {UniformGroupNode}
  3648. */
  3649. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame', 0, NodeUpdateType.FRAME );
  3650. /**
  3651. * TSL object that represents a shared uniform group node which is updated once per render.
  3652. *
  3653. * @tsl
  3654. * @type {UniformGroupNode}
  3655. */
  3656. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render', 0, NodeUpdateType.RENDER );
  3657. /**
  3658. * TSL object that represents a uniform group node which is updated once per object.
  3659. *
  3660. * @tsl
  3661. * @type {UniformGroupNode}
  3662. */
  3663. const objectGroup = /*@__PURE__*/ uniformGroup( 'object', 1, NodeUpdateType.OBJECT );
  3664. /**
  3665. * Class for representing a uniform.
  3666. *
  3667. * @augments InputNode
  3668. */
  3669. class UniformNode extends InputNode {
  3670. static get type() {
  3671. return 'UniformNode';
  3672. }
  3673. /**
  3674. * Constructs a new uniform node.
  3675. *
  3676. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3677. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3678. */
  3679. constructor( value, nodeType = null ) {
  3680. super( value, nodeType );
  3681. /**
  3682. * This flag can be used for type testing.
  3683. *
  3684. * @type {boolean}
  3685. * @readonly
  3686. * @default true
  3687. */
  3688. this.isUniformNode = true;
  3689. /**
  3690. * The name or label of the uniform.
  3691. *
  3692. * @type {string}
  3693. * @default ''
  3694. */
  3695. this.name = '';
  3696. /**
  3697. * The uniform group of this uniform. By default, uniforms are
  3698. * managed per object but they might belong to a shared group
  3699. * which is updated per frame or render call.
  3700. *
  3701. * @type {UniformGroupNode}
  3702. */
  3703. this.groupNode = objectGroup;
  3704. }
  3705. /**
  3706. * Sets the {@link UniformNode#name} property.
  3707. *
  3708. * @param {string} name - The name of the uniform.
  3709. * @return {UniformNode} A reference to this node.
  3710. */
  3711. setName( name ) {
  3712. this.name = name;
  3713. return this;
  3714. }
  3715. /**
  3716. * Sets the {@link UniformNode#name} property.
  3717. *
  3718. * @deprecated
  3719. * @param {string} name - The name of the uniform.
  3720. * @return {UniformNode} A reference to this node.
  3721. */
  3722. label( name ) {
  3723. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.', new StackTrace() ); // @deprecated r179
  3724. return this.setName( name );
  3725. }
  3726. /**
  3727. * Sets the {@link UniformNode#groupNode} property.
  3728. *
  3729. * @param {UniformGroupNode} group - The uniform group.
  3730. * @return {UniformNode} A reference to this node.
  3731. */
  3732. setGroup( group ) {
  3733. this.groupNode = group;
  3734. return this;
  3735. }
  3736. /**
  3737. * Returns the {@link UniformNode#groupNode}.
  3738. *
  3739. * @return {UniformGroupNode} The uniform group.
  3740. */
  3741. getGroup() {
  3742. return this.groupNode;
  3743. }
  3744. /**
  3745. * By default, this method returns the result of {@link Node#getHash} but derived
  3746. * classes might overwrite this method with a different implementation.
  3747. *
  3748. * @param {NodeBuilder} builder - The current node builder.
  3749. * @return {string} The uniform hash.
  3750. */
  3751. getUniformHash( builder ) {
  3752. return this.getHash( builder );
  3753. }
  3754. onUpdate( callback, updateType ) {
  3755. callback = callback.bind( this );
  3756. return super.onUpdate( ( frame ) => {
  3757. const value = callback( frame, this );
  3758. if ( value !== undefined ) {
  3759. this.value = value;
  3760. }
  3761. }, updateType );
  3762. }
  3763. getInputType( builder ) {
  3764. let type = super.getInputType( builder );
  3765. if ( type === 'bool' ) {
  3766. type = 'uint';
  3767. }
  3768. return type;
  3769. }
  3770. generate( builder, output ) {
  3771. const type = this.getNodeType( builder );
  3772. const hash = this.getUniformHash( builder );
  3773. let sharedNode = builder.getNodeFromHash( hash );
  3774. if ( sharedNode === undefined ) {
  3775. builder.setHashNode( this, hash );
  3776. sharedNode = this;
  3777. }
  3778. const sharedNodeType = sharedNode.getInputType( builder );
  3779. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3780. const uniformName = builder.getPropertyName( nodeUniform );
  3781. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3782. //
  3783. let snippet = uniformName;
  3784. if ( type === 'bool' ) {
  3785. // cache to variable
  3786. const nodeData = builder.getDataFromNode( this );
  3787. let propertyName = nodeData.propertyName;
  3788. if ( propertyName === undefined ) {
  3789. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3790. propertyName = builder.getPropertyName( nodeVar );
  3791. nodeData.propertyName = propertyName;
  3792. snippet = builder.format( uniformName, sharedNodeType, type );
  3793. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3794. }
  3795. snippet = propertyName;
  3796. }
  3797. return builder.format( snippet, type, output );
  3798. }
  3799. }
  3800. /**
  3801. * TSL function for creating a uniform node.
  3802. *
  3803. * @tsl
  3804. * @function
  3805. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3806. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3807. * @returns {UniformNode}
  3808. */
  3809. const uniform = ( value, type ) => {
  3810. const nodeType = getConstNodeType( type || value );
  3811. if ( nodeType === value ) {
  3812. // if the value is a type but no having a value
  3813. value = getValueFromType( nodeType );
  3814. }
  3815. if ( value && value.isNode === true ) {
  3816. let v = value.value;
  3817. value.traverse( n => {
  3818. if ( n.isConstNode === true ) {
  3819. v = n.value;
  3820. }
  3821. } );
  3822. value = v;
  3823. }
  3824. return new UniformNode( value, nodeType );
  3825. };
  3826. /**
  3827. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3828. * ```js
  3829. * const colors = array( [
  3830. * vec3( 1, 0, 0 ),
  3831. * vec3( 0, 1, 0 ),
  3832. * vec3( 0, 0, 1 )
  3833. * ] );
  3834. *
  3835. * const redColor = tintColors.element( 0 );
  3836. * ```
  3837. *
  3838. * @augments TempNode
  3839. */
  3840. class ArrayNode extends TempNode {
  3841. static get type() {
  3842. return 'ArrayNode';
  3843. }
  3844. /**
  3845. * Constructs a new array node.
  3846. *
  3847. * @param {?string} nodeType - The data type of the elements.
  3848. * @param {number} count - Size of the array.
  3849. * @param {?Array<Node>} [values=null] - Array default values.
  3850. */
  3851. constructor( nodeType, count, values = null ) {
  3852. super( nodeType );
  3853. /**
  3854. * Array size.
  3855. *
  3856. * @type {number}
  3857. */
  3858. this.count = count;
  3859. /**
  3860. * Array default values.
  3861. *
  3862. * @type {?Array<Node>}
  3863. */
  3864. this.values = values;
  3865. /**
  3866. * This flag can be used for type testing.
  3867. *
  3868. * @type {boolean}
  3869. * @readonly
  3870. * @default true
  3871. */
  3872. this.isArrayNode = true;
  3873. }
  3874. /**
  3875. * Returns the number of elements in the node array.
  3876. *
  3877. * @param {NodeBuilder} builder - The current node builder.
  3878. * @return {number} The number of elements in the node array.
  3879. */
  3880. getArrayCount( /*builder*/ ) {
  3881. return this.count;
  3882. }
  3883. /**
  3884. * Returns the node's type.
  3885. *
  3886. * @param {NodeBuilder} builder - The current node builder.
  3887. * @return {string} The type of the node.
  3888. */
  3889. generateNodeType( builder ) {
  3890. if ( this.nodeType === null ) {
  3891. return this.values[ 0 ].getNodeType( builder );
  3892. }
  3893. return this.nodeType;
  3894. }
  3895. /**
  3896. * Returns the node's type.
  3897. *
  3898. * @param {NodeBuilder} builder - The current node builder.
  3899. * @return {string} The type of the node.
  3900. */
  3901. getElementType( builder ) {
  3902. return this.getNodeType( builder );
  3903. }
  3904. /**
  3905. * Returns the type of a member variable.
  3906. *
  3907. * @param {NodeBuilder} builder - The current node builder.
  3908. * @param {string} name - The name of the member variable.
  3909. * @return {string} The type of the member variable.
  3910. */
  3911. getMemberType( builder, name ) {
  3912. if ( this.nodeType === null ) {
  3913. return this.values[ 0 ].getMemberType( builder, name );
  3914. }
  3915. return super.getMemberType( builder, name );
  3916. }
  3917. /**
  3918. * This method builds the output node and returns the resulting array as a shader string.
  3919. *
  3920. * @param {NodeBuilder} builder - The current node builder.
  3921. * @return {string} The generated shader string.
  3922. */
  3923. generate( builder ) {
  3924. const type = this.getNodeType( builder );
  3925. return builder.generateArray( type, this.count, this.values );
  3926. }
  3927. }
  3928. /**
  3929. * TSL function for creating an array node.
  3930. *
  3931. * @tsl
  3932. * @function
  3933. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3934. * or an array containing the default values (e.g., [ vec3() ]).
  3935. * @param {?number} [count] - Size of the array.
  3936. * @returns {ArrayNode}
  3937. */
  3938. const array = ( ...params ) => {
  3939. let node;
  3940. if ( params.length === 1 ) {
  3941. const values = params[ 0 ];
  3942. node = new ArrayNode( null, values.length, values );
  3943. } else {
  3944. const nodeType = params[ 0 ];
  3945. const count = params[ 1 ];
  3946. node = new ArrayNode( nodeType, count );
  3947. }
  3948. return nodeObject( node );
  3949. };
  3950. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3951. /**
  3952. * These node represents an assign operation. Meaning a node is assigned
  3953. * to another node.
  3954. *
  3955. * @augments TempNode
  3956. */
  3957. class AssignNode extends TempNode {
  3958. static get type() {
  3959. return 'AssignNode';
  3960. }
  3961. /**
  3962. * Constructs a new assign node.
  3963. *
  3964. * @param {Node} targetNode - The target node.
  3965. * @param {Node} sourceNode - The source type.
  3966. */
  3967. constructor( targetNode, sourceNode ) {
  3968. super();
  3969. /**
  3970. * The target node.
  3971. *
  3972. * @type {Node}
  3973. */
  3974. this.targetNode = targetNode;
  3975. /**
  3976. * The source node.
  3977. *
  3978. * @type {Node}
  3979. */
  3980. this.sourceNode = sourceNode;
  3981. /**
  3982. * This flag can be used for type testing.
  3983. *
  3984. * @type {boolean}
  3985. * @readonly
  3986. * @default true
  3987. */
  3988. this.isAssignNode = true;
  3989. }
  3990. /**
  3991. * Whether this node is used more than once in context of other nodes. This method
  3992. * is overwritten since it always returns `false` (assigns are unique).
  3993. *
  3994. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3995. */
  3996. hasDependencies() {
  3997. return false;
  3998. }
  3999. generateNodeType( builder, output ) {
  4000. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  4001. }
  4002. /**
  4003. * Whether a split is required when assigning source to target. This can happen when the component length of
  4004. * target and source data type does not match.
  4005. *
  4006. * @param {NodeBuilder} builder - The current node builder.
  4007. * @return {boolean} Whether a split is required when assigning source to target.
  4008. */
  4009. needsSplitAssign( builder ) {
  4010. const { targetNode } = this;
  4011. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  4012. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  4013. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  4014. return assignDifferentVector;
  4015. }
  4016. return false;
  4017. }
  4018. setup( builder ) {
  4019. const { targetNode, sourceNode } = this;
  4020. const scope = targetNode.getScope();
  4021. const scopeData = builder.getDataFromNode( scope );
  4022. scopeData.assign = true;
  4023. const properties = builder.getNodeProperties( this );
  4024. properties.sourceNode = sourceNode;
  4025. properties.targetNode = targetNode.context( { assign: true } );
  4026. }
  4027. generate( builder, output ) {
  4028. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  4029. const needsSplitAssign = this.needsSplitAssign( builder );
  4030. const target = targetNode.build( builder );
  4031. const targetType = targetNode.getNodeType( builder );
  4032. const source = sourceNode.build( builder, targetType );
  4033. const sourceType = sourceNode.getNodeType( builder );
  4034. const nodeData = builder.getDataFromNode( this );
  4035. //
  4036. let snippet;
  4037. if ( nodeData.initialized === true ) {
  4038. if ( output !== 'void' ) {
  4039. snippet = target;
  4040. }
  4041. } else if ( needsSplitAssign ) {
  4042. const sourceVar = builder.getVarFromNode( this, null, targetType );
  4043. const sourceProperty = builder.getPropertyName( sourceVar );
  4044. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  4045. const splitNode = targetNode.node;
  4046. const splitTargetNode = splitNode.node.context( { assign: true } );
  4047. const targetRoot = splitTargetNode.build( builder );
  4048. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  4049. const component = splitNode.components[ i ];
  4050. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  4051. }
  4052. if ( output !== 'void' ) {
  4053. snippet = target;
  4054. }
  4055. } else {
  4056. snippet = `${ target } = ${ source }`;
  4057. if ( output === 'void' || sourceType === 'void' ) {
  4058. builder.addLineFlowCode( snippet, this );
  4059. if ( output !== 'void' ) {
  4060. snippet = target;
  4061. }
  4062. }
  4063. }
  4064. nodeData.initialized = true;
  4065. return builder.format( snippet, targetType, output );
  4066. }
  4067. }
  4068. /**
  4069. * TSL function for creating an assign node.
  4070. *
  4071. * @tsl
  4072. * @function
  4073. * @param {Node} targetNode - The target node.
  4074. * @param {Node} sourceNode - The source type.
  4075. * @returns {AssignNode}
  4076. */
  4077. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  4078. addMethodChaining( 'assign', assign );
  4079. /**
  4080. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  4081. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  4082. * this logic.
  4083. *
  4084. * @augments TempNode
  4085. */
  4086. class FunctionCallNode extends TempNode {
  4087. static get type() {
  4088. return 'FunctionCallNode';
  4089. }
  4090. /**
  4091. * Constructs a new function call node.
  4092. *
  4093. * @param {?FunctionNode} functionNode - The function node.
  4094. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  4095. */
  4096. constructor( functionNode = null, parameters = {} ) {
  4097. super();
  4098. /**
  4099. * The function node.
  4100. *
  4101. * @type {?FunctionNode}
  4102. * @default null
  4103. */
  4104. this.functionNode = functionNode;
  4105. /**
  4106. * The parameters of the function call.
  4107. *
  4108. * @type {Object<string, Node>}
  4109. * @default {}
  4110. */
  4111. this.parameters = parameters;
  4112. }
  4113. /**
  4114. * Sets the parameters of the function call node.
  4115. *
  4116. * @param {Object<string, Node>} parameters - The parameters to set.
  4117. * @return {FunctionCallNode} A reference to this node.
  4118. */
  4119. setParameters( parameters ) {
  4120. this.parameters = parameters;
  4121. return this;
  4122. }
  4123. /**
  4124. * Returns the parameters of the function call node.
  4125. *
  4126. * @return {Object<string, Node>} The parameters of this node.
  4127. */
  4128. getParameters() {
  4129. return this.parameters;
  4130. }
  4131. /**
  4132. * Returns the type of this function call node.
  4133. *
  4134. * @param {NodeBuilder} builder - The current node builder.
  4135. * @returns {string} The type of this node.
  4136. */
  4137. generateNodeType( builder ) {
  4138. return this.functionNode.getNodeType( builder );
  4139. }
  4140. /**
  4141. * Returns the function node of this function call node.
  4142. *
  4143. * @param {NodeBuilder} builder - The current node builder.
  4144. * @param {string} [name] - The name of the member.
  4145. * @returns {string} The type of the member.
  4146. */
  4147. getMemberType( builder, name ) {
  4148. return this.functionNode.getMemberType( builder, name );
  4149. }
  4150. generate( builder ) {
  4151. const params = [];
  4152. const functionNode = this.functionNode;
  4153. const inputs = functionNode.getInputs( builder );
  4154. const parameters = this.parameters;
  4155. const generateInput = ( node, inputNode ) => {
  4156. const type = inputNode.type;
  4157. const pointer = type === 'pointer';
  4158. let output;
  4159. if ( pointer ) output = '&' + node.build( builder );
  4160. else output = node.build( builder, type );
  4161. return output;
  4162. };
  4163. if ( Array.isArray( parameters ) ) {
  4164. if ( parameters.length > inputs.length ) {
  4165. error( 'TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  4166. parameters.length = inputs.length;
  4167. } else if ( parameters.length < inputs.length ) {
  4168. error( 'TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  4169. while ( parameters.length < inputs.length ) {
  4170. parameters.push( float( 0 ) );
  4171. }
  4172. }
  4173. for ( let i = 0; i < parameters.length; i ++ ) {
  4174. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  4175. }
  4176. } else {
  4177. for ( const inputNode of inputs ) {
  4178. const node = parameters[ inputNode.name ];
  4179. if ( node !== undefined ) {
  4180. params.push( generateInput( node, inputNode ) );
  4181. } else {
  4182. error( `TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  4183. params.push( generateInput( float( 0 ), inputNode ) );
  4184. }
  4185. }
  4186. }
  4187. const functionName = functionNode.build( builder, 'property' );
  4188. return `${ functionName }( ${ params.join( ', ' ) } )`;
  4189. }
  4190. }
  4191. const call = ( func, ...params ) => {
  4192. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  4193. return new FunctionCallNode( nodeObject( func ), params );
  4194. };
  4195. addMethodChaining( 'call', call );
  4196. const _vectorOperators = {
  4197. '==': 'equal',
  4198. '!=': 'notEqual',
  4199. '<': 'lessThan',
  4200. '>': 'greaterThan',
  4201. '<=': 'lessThanEqual',
  4202. '>=': 'greaterThanEqual',
  4203. '%': 'mod'
  4204. };
  4205. /**
  4206. * This node represents basic mathematical and logical operations like addition,
  4207. * subtraction or comparisons (e.g. `equal()`).
  4208. *
  4209. * @augments TempNode
  4210. */
  4211. class OperatorNode extends TempNode {
  4212. static get type() {
  4213. return 'OperatorNode';
  4214. }
  4215. /**
  4216. * Constructs a new operator node.
  4217. *
  4218. * @param {string} op - The operator.
  4219. * @param {Node} aNode - The first input.
  4220. * @param {Node} bNode - The second input.
  4221. * @param {...Node} params - Additional input parameters.
  4222. */
  4223. constructor( op, aNode, bNode, ...params ) {
  4224. super();
  4225. if ( params.length > 0 ) {
  4226. let finalOp = new OperatorNode( op, aNode, bNode );
  4227. for ( let i = 0; i < params.length - 1; i ++ ) {
  4228. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  4229. }
  4230. aNode = finalOp;
  4231. bNode = params[ params.length - 1 ];
  4232. }
  4233. /**
  4234. * The operator.
  4235. *
  4236. * @type {string}
  4237. */
  4238. this.op = op;
  4239. /**
  4240. * The first input.
  4241. *
  4242. * @type {Node}
  4243. */
  4244. this.aNode = aNode;
  4245. /**
  4246. * The second input.
  4247. *
  4248. * @type {Node}
  4249. */
  4250. this.bNode = bNode;
  4251. /**
  4252. * This flag can be used for type testing.
  4253. *
  4254. * @type {boolean}
  4255. * @readonly
  4256. * @default true
  4257. */
  4258. this.isOperatorNode = true;
  4259. }
  4260. /**
  4261. * Returns the operator method name.
  4262. *
  4263. * @param {NodeBuilder} builder - The current node builder.
  4264. * @param {string} output - The output type.
  4265. * @returns {string} The operator method name.
  4266. */
  4267. getOperatorMethod( builder, output ) {
  4268. return builder.getMethod( _vectorOperators[ this.op ], output );
  4269. }
  4270. /**
  4271. * This method is overwritten since the node type is inferred from the operator
  4272. * and the input node types.
  4273. *
  4274. * @param {NodeBuilder} builder - The current node builder.
  4275. * @param {?string} [output=null] - The output type.
  4276. * @return {string} The node type.
  4277. */
  4278. generateNodeType( builder, output = null ) {
  4279. const op = this.op;
  4280. const aNode = this.aNode;
  4281. const bNode = this.bNode;
  4282. const typeA = aNode.getNodeType( builder );
  4283. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  4284. if ( typeA === 'void' || typeB === 'void' ) {
  4285. return output || 'void';
  4286. } else if ( op === '%' ) {
  4287. return typeA;
  4288. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  4289. return builder.getIntegerType( typeA );
  4290. } else if ( op === '&&' || op === '||' || op === '^^' ) {
  4291. return 'bool';
  4292. } else if ( op === '!' ) {
  4293. const typeLength = builder.getTypeLength( typeA );
  4294. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  4295. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  4296. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  4297. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  4298. } else {
  4299. // Handle matrix operations
  4300. if ( builder.isMatrix( typeA ) ) {
  4301. if ( typeB === 'float' ) {
  4302. return typeA; // matrix * scalar = matrix
  4303. } else if ( builder.isVector( typeB ) ) {
  4304. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  4305. } else if ( builder.isMatrix( typeB ) ) {
  4306. return typeA; // matrix * matrix
  4307. }
  4308. } else if ( builder.isMatrix( typeB ) ) {
  4309. if ( typeA === 'float' ) {
  4310. return typeB; // scalar * matrix = matrix
  4311. } else if ( builder.isVector( typeA ) ) {
  4312. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  4313. }
  4314. }
  4315. // Handle non-matrix cases
  4316. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  4317. // anytype x anytype: use the greater length vector
  4318. return typeB;
  4319. }
  4320. return typeA;
  4321. }
  4322. }
  4323. generate( builder, output ) {
  4324. const op = this.op;
  4325. const { aNode, bNode } = this;
  4326. const type = this.getNodeType( builder, output );
  4327. let typeA = null;
  4328. let typeB = null;
  4329. if ( type !== 'void' ) {
  4330. typeA = aNode.getNodeType( builder );
  4331. typeB = bNode ? bNode.getNodeType( builder ) : null;
  4332. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  4333. if ( builder.isVector( typeA ) ) {
  4334. typeB = typeA;
  4335. } else if ( builder.isVector( typeB ) ) {
  4336. typeA = typeB;
  4337. } else if ( typeA !== typeB ) {
  4338. typeA = typeB = 'float';
  4339. }
  4340. } else if ( op === '>>' || op === '<<' ) {
  4341. typeA = type;
  4342. typeB = builder.changeComponentType( typeB, 'uint' );
  4343. } else if ( op === '%' ) {
  4344. typeA = type;
  4345. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  4346. } else if ( builder.isMatrix( typeA ) ) {
  4347. if ( typeB === 'float' ) {
  4348. // Keep matrix type for typeA, but ensure typeB stays float
  4349. typeB = 'float';
  4350. } else if ( builder.isVector( typeB ) ) {
  4351. // matrix x vector
  4352. typeB = builder.getVectorFromMatrix( typeA );
  4353. } else if ( builder.isMatrix( typeB ) ) ; else {
  4354. typeA = typeB = type;
  4355. }
  4356. } else if ( builder.isMatrix( typeB ) ) {
  4357. if ( typeA === 'float' ) {
  4358. // Keep matrix type for typeB, but ensure typeA stays float
  4359. typeA = 'float';
  4360. } else if ( builder.isVector( typeA ) ) {
  4361. // vector x matrix
  4362. typeA = builder.getVectorFromMatrix( typeB );
  4363. } else {
  4364. typeA = typeB = type;
  4365. }
  4366. } else {
  4367. // anytype x anytype
  4368. typeA = typeB = type;
  4369. }
  4370. } else {
  4371. typeA = typeB = type;
  4372. }
  4373. const a = aNode.build( builder, typeA );
  4374. const b = bNode ? bNode.build( builder, typeB ) : null;
  4375. const fnOpSnippet = builder.getFunctionOperator( op );
  4376. if ( output !== 'void' ) {
  4377. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  4378. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  4379. if ( isGLSL ) {
  4380. if ( builder.isVector( typeA ) ) {
  4381. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  4382. } else {
  4383. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4384. }
  4385. } else {
  4386. // WGSL
  4387. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4388. }
  4389. } else if ( op === '%' ) {
  4390. if ( builder.isInteger( typeB ) ) {
  4391. return builder.format( `( ${ a } % ${ b } )`, type, output );
  4392. } else {
  4393. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  4394. }
  4395. } else if ( op === '!' ) {
  4396. if ( isGLSL && builder.isVector( typeA ) ) {
  4397. return builder.format( `not( ${a} )`, output );
  4398. } else {
  4399. // WGSL and scalars on GLSL
  4400. return builder.format( `( ${op} ${a} )`, typeA, output );
  4401. }
  4402. } else if ( op === '~' ) {
  4403. return builder.format( `( ${op} ${a} )`, typeA, output );
  4404. } else if ( fnOpSnippet ) {
  4405. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4406. } else {
  4407. // Handle matrix operations
  4408. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4409. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  4410. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  4411. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4412. } else {
  4413. let snippet = `( ${ a } ${ op } ${ b } )`;
  4414. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  4415. snippet = `all${ snippet }`;
  4416. }
  4417. return builder.format( snippet, type, output );
  4418. }
  4419. }
  4420. } else if ( typeA !== 'void' ) {
  4421. if ( fnOpSnippet ) {
  4422. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4423. } else {
  4424. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4425. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  4426. } else {
  4427. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4428. }
  4429. }
  4430. }
  4431. }
  4432. serialize( data ) {
  4433. super.serialize( data );
  4434. data.op = this.op;
  4435. }
  4436. deserialize( data ) {
  4437. super.deserialize( data );
  4438. this.op = data.op;
  4439. }
  4440. }
  4441. /**
  4442. * Returns the addition of two or more value.
  4443. *
  4444. * @tsl
  4445. * @function
  4446. * @param {Node} a - The first input.
  4447. * @param {Node} b - The second input.
  4448. * @param {...Node} params - Additional input parameters.
  4449. * @returns {OperatorNode}
  4450. */
  4451. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  4452. /**
  4453. * Returns the subtraction of two or more value.
  4454. *
  4455. * @tsl
  4456. * @function
  4457. * @param {Node} a - The first input.
  4458. * @param {Node} b - The second input.
  4459. * @param {...Node} params - Additional input parameters.
  4460. * @returns {OperatorNode}
  4461. */
  4462. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  4463. /**
  4464. * Returns the multiplication of two or more value.
  4465. *
  4466. * @tsl
  4467. * @function
  4468. * @param {Node} a - The first input.
  4469. * @param {Node} b - The second input.
  4470. * @param {...Node} params - Additional input parameters.
  4471. * @returns {OperatorNode}
  4472. */
  4473. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  4474. /**
  4475. * Returns the division of two or more value.
  4476. *
  4477. * @tsl
  4478. * @function
  4479. * @param {Node} a - The first input.
  4480. * @param {Node} b - The second input.
  4481. * @param {...Node} params - Additional input parameters.
  4482. * @returns {OperatorNode}
  4483. */
  4484. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  4485. /**
  4486. * Computes the remainder of dividing the first node by the second one.
  4487. *
  4488. * @tsl
  4489. * @function
  4490. * @param {Node} a - The first input.
  4491. * @param {Node} b - The second input.
  4492. * @returns {OperatorNode}
  4493. */
  4494. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  4495. /**
  4496. * Checks if two nodes are equal.
  4497. *
  4498. * @tsl
  4499. * @function
  4500. * @param {Node} a - The first input.
  4501. * @param {Node} b - The second input.
  4502. * @returns {OperatorNode}
  4503. */
  4504. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  4505. /**
  4506. * Checks if two nodes are not equal.
  4507. *
  4508. * @tsl
  4509. * @function
  4510. * @param {Node} a - The first input.
  4511. * @param {Node} b - The second input.
  4512. * @returns {OperatorNode}
  4513. */
  4514. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  4515. /**
  4516. * Checks if the first node is less than the second.
  4517. *
  4518. * @tsl
  4519. * @function
  4520. * @param {Node} a - The first input.
  4521. * @param {Node} b - The second input.
  4522. * @returns {OperatorNode}
  4523. */
  4524. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  4525. /**
  4526. * Checks if the first node is greater than the second.
  4527. *
  4528. * @tsl
  4529. * @function
  4530. * @param {Node} a - The first input.
  4531. * @param {Node} b - The second input.
  4532. * @returns {OperatorNode}
  4533. */
  4534. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  4535. /**
  4536. * Checks if the first node is less than or equal to the second.
  4537. *
  4538. * @tsl
  4539. * @function
  4540. * @param {Node} a - The first input.
  4541. * @param {Node} b - The second input.
  4542. * @returns {OperatorNode}
  4543. */
  4544. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  4545. /**
  4546. * Checks if the first node is greater than or equal to the second.
  4547. *
  4548. * @tsl
  4549. * @function
  4550. * @param {Node} a - The first input.
  4551. * @param {Node} b - The second input.
  4552. * @returns {OperatorNode}
  4553. */
  4554. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  4555. /**
  4556. * Performs a logical AND operation on multiple nodes.
  4557. *
  4558. * @tsl
  4559. * @function
  4560. * @param {...Node} nodes - The input nodes to be combined using AND.
  4561. * @returns {OperatorNode}
  4562. */
  4563. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  4564. /**
  4565. * Performs a logical OR operation on multiple nodes.
  4566. *
  4567. * @tsl
  4568. * @function
  4569. * @param {...Node} nodes - The input nodes to be combined using OR.
  4570. * @returns {OperatorNode}
  4571. */
  4572. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  4573. /**
  4574. * Performs logical NOT on a node.
  4575. *
  4576. * @tsl
  4577. * @function
  4578. * @param {Node} value - The value.
  4579. * @returns {OperatorNode}
  4580. */
  4581. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  4582. /**
  4583. * Performs logical XOR on two nodes.
  4584. *
  4585. * @tsl
  4586. * @function
  4587. * @param {Node} a - The first input.
  4588. * @param {Node} b - The second input.
  4589. * @returns {OperatorNode}
  4590. */
  4591. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  4592. /**
  4593. * Performs bitwise AND on two nodes.
  4594. *
  4595. * @tsl
  4596. * @function
  4597. * @param {Node} a - The first input.
  4598. * @param {Node} b - The second input.
  4599. * @returns {OperatorNode}
  4600. */
  4601. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4602. /**
  4603. * Performs bitwise NOT on a node.
  4604. *
  4605. * @tsl
  4606. * @function
  4607. * @param {Node} a - The first input.
  4608. * @param {Node} b - The second input.
  4609. * @returns {OperatorNode}
  4610. */
  4611. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 1 ).setName( 'bitNot' );
  4612. /**
  4613. * Performs bitwise OR on two nodes.
  4614. *
  4615. * @tsl
  4616. * @function
  4617. * @param {Node} a - The first input.
  4618. * @param {Node} b - The second input.
  4619. * @returns {OperatorNode}
  4620. */
  4621. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4622. /**
  4623. * Performs bitwise XOR on two nodes.
  4624. *
  4625. * @tsl
  4626. * @function
  4627. * @param {Node} a - The first input.
  4628. * @param {Node} b - The second input.
  4629. * @returns {OperatorNode}
  4630. */
  4631. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4632. /**
  4633. * Shifts a node to the left.
  4634. *
  4635. * @tsl
  4636. * @function
  4637. * @param {Node} a - The node to shift.
  4638. * @param {Node} b - The value to shift.
  4639. * @returns {OperatorNode}
  4640. */
  4641. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4642. /**
  4643. * Shifts a node to the right.
  4644. *
  4645. * @tsl
  4646. * @function
  4647. * @param {Node} a - The node to shift.
  4648. * @param {Node} b - The value to shift.
  4649. * @returns {OperatorNode}
  4650. */
  4651. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4652. /**
  4653. * Increments a node by 1.
  4654. *
  4655. * @tsl
  4656. * @function
  4657. * @param {Node} a - The node to increment.
  4658. * @returns {OperatorNode}
  4659. */
  4660. const incrementBefore = Fn( ( [ a ] ) => {
  4661. a.addAssign( 1 );
  4662. return a;
  4663. } );
  4664. /**
  4665. * Decrements a node by 1.
  4666. *
  4667. * @tsl
  4668. * @function
  4669. * @param {Node} a - The node to decrement.
  4670. * @returns {OperatorNode}
  4671. */
  4672. const decrementBefore = Fn( ( [ a ] ) => {
  4673. a.subAssign( 1 );
  4674. return a;
  4675. } );
  4676. /**
  4677. * Increments a node by 1 and returns the previous value.
  4678. *
  4679. * @tsl
  4680. * @function
  4681. * @param {Node} a - The node to increment.
  4682. * @returns {OperatorNode}
  4683. */
  4684. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4685. const temp = int( a ).toConst();
  4686. a.addAssign( 1 );
  4687. return temp;
  4688. } );
  4689. /**
  4690. * Decrements a node by 1 and returns the previous value.
  4691. *
  4692. * @tsl
  4693. * @function
  4694. * @param {Node} a - The node to decrement.
  4695. * @returns {OperatorNode}
  4696. */
  4697. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4698. const temp = int( a ).toConst();
  4699. a.subAssign( 1 );
  4700. return temp;
  4701. } );
  4702. addMethodChaining( 'add', add );
  4703. addMethodChaining( 'sub', sub );
  4704. addMethodChaining( 'mul', mul );
  4705. addMethodChaining( 'div', div );
  4706. addMethodChaining( 'mod', mod );
  4707. addMethodChaining( 'equal', equal );
  4708. addMethodChaining( 'notEqual', notEqual );
  4709. addMethodChaining( 'lessThan', lessThan );
  4710. addMethodChaining( 'greaterThan', greaterThan );
  4711. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4712. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4713. addMethodChaining( 'and', and );
  4714. addMethodChaining( 'or', or );
  4715. addMethodChaining( 'not', not );
  4716. addMethodChaining( 'xor', xor );
  4717. addMethodChaining( 'bitAnd', bitAnd );
  4718. addMethodChaining( 'bitNot', bitNot );
  4719. addMethodChaining( 'bitOr', bitOr );
  4720. addMethodChaining( 'bitXor', bitXor );
  4721. addMethodChaining( 'shiftLeft', shiftLeft );
  4722. addMethodChaining( 'shiftRight', shiftRight );
  4723. addMethodChaining( 'incrementBefore', incrementBefore );
  4724. addMethodChaining( 'decrementBefore', decrementBefore );
  4725. addMethodChaining( 'increment', increment );
  4726. addMethodChaining( 'decrement', decrement );
  4727. /**
  4728. * This node represents a variety of mathematical methods available in shaders.
  4729. * They are divided into three categories:
  4730. *
  4731. * - Methods with one input like `sin`, `cos` or `normalize`.
  4732. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4733. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4734. *
  4735. * @augments TempNode
  4736. */
  4737. class MathNode extends TempNode {
  4738. static get type() {
  4739. return 'MathNode';
  4740. }
  4741. /**
  4742. * Constructs a new math node.
  4743. *
  4744. * @param {string} method - The method name.
  4745. * @param {Node} aNode - The first input.
  4746. * @param {?Node} [bNode=null] - The second input.
  4747. * @param {?Node} [cNode=null] - The third input.
  4748. */
  4749. constructor( method, aNode, bNode = null, cNode = null ) {
  4750. super();
  4751. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4752. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4753. let finalOp = new MathNode( method, aNode, bNode );
  4754. for ( let i = 3; i < arguments.length - 1; i ++ ) {
  4755. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4756. }
  4757. aNode = finalOp;
  4758. bNode = arguments[ arguments.length - 1 ];
  4759. cNode = null;
  4760. }
  4761. /**
  4762. * The method name.
  4763. *
  4764. * @type {string}
  4765. */
  4766. this.method = method;
  4767. /**
  4768. * The first input.
  4769. *
  4770. * @type {Node}
  4771. */
  4772. this.aNode = aNode;
  4773. /**
  4774. * The second input.
  4775. *
  4776. * @type {?Node}
  4777. * @default null
  4778. */
  4779. this.bNode = bNode;
  4780. /**
  4781. * The third input.
  4782. *
  4783. * @type {?Node}
  4784. * @default null
  4785. */
  4786. this.cNode = cNode;
  4787. /**
  4788. * This flag can be used for type testing.
  4789. *
  4790. * @type {boolean}
  4791. * @readonly
  4792. * @default true
  4793. */
  4794. this.isMathNode = true;
  4795. }
  4796. /**
  4797. * The input type is inferred from the node types of the input nodes.
  4798. *
  4799. * @param {NodeBuilder} builder - The current node builder.
  4800. * @return {string} The input type.
  4801. */
  4802. getInputType( builder ) {
  4803. const aType = this.aNode.getNodeType( builder );
  4804. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4805. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4806. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4807. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4808. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4809. if ( aLen > bLen && aLen > cLen ) {
  4810. return aType;
  4811. } else if ( bLen > cLen ) {
  4812. return bType;
  4813. } else if ( cLen > aLen ) {
  4814. return cType;
  4815. }
  4816. return aType;
  4817. }
  4818. /**
  4819. * The selected method as well as the input type determine the node type of this node.
  4820. *
  4821. * @param {NodeBuilder} builder - The current node builder.
  4822. * @return {string} The node type.
  4823. */
  4824. generateNodeType( builder ) {
  4825. const method = this.method;
  4826. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4827. return 'float';
  4828. } else if ( method === MathNode.CROSS ) {
  4829. return 'vec3';
  4830. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4831. return 'bool';
  4832. } else if ( method === MathNode.EQUALS ) {
  4833. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4834. } else {
  4835. return this.getInputType( builder );
  4836. }
  4837. }
  4838. setup( builder ) {
  4839. const { aNode, bNode, method } = this;
  4840. let outputNode = null;
  4841. if ( method === MathNode.ONE_MINUS ) {
  4842. outputNode = sub( 1.0, aNode );
  4843. } else if ( method === MathNode.RECIPROCAL ) {
  4844. outputNode = div( 1.0, aNode );
  4845. } else if ( method === MathNode.DIFFERENCE ) {
  4846. outputNode = abs( sub( aNode, bNode ) );
  4847. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4848. // pre-multiplies the direction by the matrix and normalizes the result
  4849. let matrixNode, directionNode;
  4850. if ( builder.isMatrix( aNode.getNodeType( builder ) ) ) {
  4851. matrixNode = aNode;
  4852. directionNode = bNode;
  4853. } else {
  4854. matrixNode = bNode;
  4855. directionNode = aNode;
  4856. }
  4857. outputNode = normalize( mul( matrixNode, vec4( vec3( directionNode ), 0.0 ) ).xyz );
  4858. }
  4859. if ( outputNode !== null ) {
  4860. return outputNode;
  4861. } else {
  4862. return super.setup( builder );
  4863. }
  4864. }
  4865. generate( builder, output ) {
  4866. const properties = builder.getNodeProperties( this );
  4867. if ( properties.outputNode ) {
  4868. return super.generate( builder, output );
  4869. }
  4870. let method = this.method;
  4871. const type = this.getNodeType( builder );
  4872. const inputType = this.getInputType( builder );
  4873. const a = this.aNode;
  4874. const b = this.bNode;
  4875. const c = this.cNode;
  4876. const coordinateSystem = builder.renderer.coordinateSystem;
  4877. if ( method === MathNode.NEGATE ) {
  4878. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4879. } else {
  4880. const params = [];
  4881. if ( method === MathNode.CROSS ) {
  4882. params.push(
  4883. a.build( builder, type ),
  4884. b.build( builder, type )
  4885. );
  4886. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4887. params.push(
  4888. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4889. b.build( builder, inputType )
  4890. );
  4891. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4892. params.push(
  4893. a.build( builder, inputType ),
  4894. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4895. );
  4896. } else if ( method === MathNode.REFRACT ) {
  4897. params.push(
  4898. a.build( builder, inputType ),
  4899. b.build( builder, inputType ),
  4900. c.build( builder, 'float' )
  4901. );
  4902. } else if ( method === MathNode.MIX ) {
  4903. params.push(
  4904. a.build( builder, inputType ),
  4905. b.build( builder, inputType ),
  4906. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4907. );
  4908. } else {
  4909. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4910. method = 'atan2';
  4911. }
  4912. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4913. warn( `TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.`, this.stackTrace );
  4914. method = '/*' + method + '*/';
  4915. }
  4916. params.push( a.build( builder, inputType ) );
  4917. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4918. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4919. }
  4920. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4921. }
  4922. }
  4923. serialize( data ) {
  4924. super.serialize( data );
  4925. data.method = this.method;
  4926. }
  4927. deserialize( data ) {
  4928. super.deserialize( data );
  4929. this.method = data.method;
  4930. }
  4931. }
  4932. // 1 input
  4933. MathNode.ALL = 'all';
  4934. MathNode.ANY = 'any';
  4935. MathNode.RADIANS = 'radians';
  4936. MathNode.DEGREES = 'degrees';
  4937. MathNode.EXP = 'exp';
  4938. MathNode.EXP2 = 'exp2';
  4939. MathNode.LOG = 'log';
  4940. MathNode.LOG2 = 'log2';
  4941. MathNode.SQRT = 'sqrt';
  4942. MathNode.INVERSE_SQRT = 'inversesqrt';
  4943. MathNode.FLOOR = 'floor';
  4944. MathNode.CEIL = 'ceil';
  4945. MathNode.NORMALIZE = 'normalize';
  4946. MathNode.FRACT = 'fract';
  4947. MathNode.SIN = 'sin';
  4948. MathNode.SINH = 'sinh';
  4949. MathNode.COS = 'cos';
  4950. MathNode.COSH = 'cosh';
  4951. MathNode.TAN = 'tan';
  4952. MathNode.TANH = 'tanh';
  4953. MathNode.ASIN = 'asin';
  4954. MathNode.ASINH = 'asinh';
  4955. MathNode.ACOS = 'acos';
  4956. MathNode.ACOSH = 'acosh';
  4957. MathNode.ATAN = 'atan';
  4958. MathNode.ATANH = 'atanh';
  4959. MathNode.ABS = 'abs';
  4960. MathNode.SIGN = 'sign';
  4961. MathNode.LENGTH = 'length';
  4962. MathNode.NEGATE = 'negate';
  4963. MathNode.ONE_MINUS = 'oneMinus';
  4964. MathNode.DFDX = 'dFdx';
  4965. MathNode.DFDY = 'dFdy';
  4966. MathNode.ROUND = 'round';
  4967. MathNode.RECIPROCAL = 'reciprocal';
  4968. MathNode.TRUNC = 'trunc';
  4969. MathNode.FWIDTH = 'fwidth';
  4970. MathNode.TRANSPOSE = 'transpose';
  4971. MathNode.DETERMINANT = 'determinant';
  4972. MathNode.INVERSE = 'inverse';
  4973. // 2 inputs
  4974. MathNode.EQUALS = 'equals';
  4975. MathNode.MIN = 'min';
  4976. MathNode.MAX = 'max';
  4977. MathNode.STEP = 'step';
  4978. MathNode.REFLECT = 'reflect';
  4979. MathNode.DISTANCE = 'distance';
  4980. MathNode.DIFFERENCE = 'difference';
  4981. MathNode.DOT = 'dot';
  4982. MathNode.CROSS = 'cross';
  4983. MathNode.POW = 'pow';
  4984. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4985. // 3 inputs
  4986. MathNode.MIX = 'mix';
  4987. MathNode.CLAMP = 'clamp';
  4988. MathNode.REFRACT = 'refract';
  4989. MathNode.SMOOTHSTEP = 'smoothstep';
  4990. MathNode.FACEFORWARD = 'faceforward';
  4991. // 1 inputs
  4992. /**
  4993. * A small value used to handle floating-point precision errors.
  4994. *
  4995. * @tsl
  4996. * @type {Node<float>}
  4997. */
  4998. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4999. /**
  5000. * Represents infinity.
  5001. *
  5002. * @tsl
  5003. * @type {Node<float>}
  5004. */
  5005. const INFINITY = /*@__PURE__*/ float( 1e6 );
  5006. /**
  5007. * Represents PI.
  5008. *
  5009. * @tsl
  5010. * @type {Node<float>}
  5011. */
  5012. const PI = /*@__PURE__*/ float( Math.PI );
  5013. /**
  5014. * Represents PI * 2. Please use the non-deprecated version `TWO_PI`.
  5015. *
  5016. * @tsl
  5017. * @deprecated
  5018. * @type {Node<float>}
  5019. */
  5020. const PI2 = /*@__PURE__*/ float( Math.PI * 2 ); // @deprecated r181
  5021. /**
  5022. * Represents PI * 2.
  5023. *
  5024. * @tsl
  5025. * @type {Node<float>}
  5026. */
  5027. const TWO_PI = /*@__PURE__*/ float( Math.PI * 2 );
  5028. /**
  5029. * Represents PI / 2.
  5030. *
  5031. * @tsl
  5032. * @type {Node<float>}
  5033. */
  5034. const HALF_PI = /*@__PURE__*/ float( Math.PI * 0.5 );
  5035. /**
  5036. * Returns `true` if all components of `x` are `true`.
  5037. *
  5038. * @tsl
  5039. * @function
  5040. * @param {Node | number} x - The parameter.
  5041. * @returns {Node<bool>}
  5042. */
  5043. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  5044. /**
  5045. * Returns `true` if any components of `x` are `true`.
  5046. *
  5047. * @tsl
  5048. * @function
  5049. * @param {Node | number} x - The parameter.
  5050. * @returns {Node<bool>}
  5051. */
  5052. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  5053. /**
  5054. * Converts a quantity in degrees to radians.
  5055. *
  5056. * @tsl
  5057. * @function
  5058. * @param {Node | number} x - The input in degrees.
  5059. * @returns {Node}
  5060. */
  5061. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  5062. /**
  5063. * Convert a quantity in radians to degrees.
  5064. *
  5065. * @tsl
  5066. * @function
  5067. * @param {Node | number} x - The input in radians.
  5068. * @returns {Node}
  5069. */
  5070. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  5071. /**
  5072. * Returns the natural exponentiation of the parameter.
  5073. *
  5074. * @tsl
  5075. * @function
  5076. * @param {Node | number} x - The parameter.
  5077. * @returns {Node}
  5078. */
  5079. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  5080. /**
  5081. * Returns 2 raised to the power of the parameter.
  5082. *
  5083. * @tsl
  5084. * @function
  5085. * @param {Node | number} x - The parameter.
  5086. * @returns {Node}
  5087. */
  5088. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  5089. /**
  5090. * Returns the natural logarithm of the parameter.
  5091. *
  5092. * @tsl
  5093. * @function
  5094. * @param {Node | number} x - The parameter.
  5095. * @returns {Node}
  5096. */
  5097. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  5098. /**
  5099. * Returns the base 2 logarithm of the parameter.
  5100. *
  5101. * @tsl
  5102. * @function
  5103. * @param {Node | number} x - The parameter.
  5104. * @returns {Node}
  5105. */
  5106. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  5107. /**
  5108. * Returns the square root of the parameter.
  5109. *
  5110. * @tsl
  5111. * @function
  5112. * @param {Node | number} x - The parameter.
  5113. * @returns {Node}
  5114. */
  5115. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  5116. /**
  5117. * Returns the inverse of the square root of the parameter.
  5118. *
  5119. * @tsl
  5120. * @function
  5121. * @param {Node | number} x - The parameter.
  5122. * @returns {Node}
  5123. */
  5124. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  5125. /**
  5126. * Finds the nearest integer less than or equal to the parameter.
  5127. *
  5128. * @tsl
  5129. * @function
  5130. * @param {Node | number} x - The parameter.
  5131. * @returns {Node}
  5132. */
  5133. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  5134. /**
  5135. * Finds the nearest integer that is greater than or equal to the parameter.
  5136. *
  5137. * @tsl
  5138. * @function
  5139. * @param {Node | number} x - The parameter.
  5140. * @returns {Node}
  5141. */
  5142. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  5143. /**
  5144. * Calculates the unit vector in the same direction as the original vector.
  5145. *
  5146. * @tsl
  5147. * @function
  5148. * @param {Node} x - The input vector.
  5149. * @returns {Node}
  5150. */
  5151. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  5152. /**
  5153. * Computes the fractional part of the parameter.
  5154. *
  5155. * @tsl
  5156. * @function
  5157. * @param {Node | number} x - The parameter.
  5158. * @returns {Node}
  5159. */
  5160. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  5161. /**
  5162. * Returns the sine of the parameter.
  5163. *
  5164. * @tsl
  5165. * @function
  5166. * @param {Node | number} x - The parameter.
  5167. * @returns {Node}
  5168. */
  5169. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  5170. /**
  5171. * Returns the hyperbolic sine of the parameter.
  5172. *
  5173. * @tsl
  5174. * @function
  5175. * @param {Node | number} x - The parameter.
  5176. * @returns {Node}
  5177. */
  5178. const sinh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SINH ).setParameterLength( 1 );
  5179. /**
  5180. * Returns the cosine of the parameter.
  5181. *
  5182. * @tsl
  5183. * @function
  5184. * @param {Node | number} x - The parameter.
  5185. * @returns {Node}
  5186. */
  5187. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  5188. /**
  5189. * Returns the hyperbolic cosine of the parameter.
  5190. *
  5191. * @tsl
  5192. * @function
  5193. * @param {Node | number} x - The parameter.
  5194. * @returns {Node}
  5195. */
  5196. const cosh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COSH ).setParameterLength( 1 );
  5197. /**
  5198. * Returns the tangent of the parameter.
  5199. *
  5200. * @tsl
  5201. * @function
  5202. * @param {Node | number} x - The parameter.
  5203. * @returns {Node}
  5204. */
  5205. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  5206. /**
  5207. * Returns the hyperbolic tangent of the parameter.
  5208. *
  5209. * @tsl
  5210. * @function
  5211. * @param {Node | number} x - The parameter.
  5212. * @returns {Node}
  5213. */
  5214. const tanh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TANH ).setParameterLength( 1 );
  5215. /**
  5216. * Returns the arcsine of the parameter.
  5217. *
  5218. * @tsl
  5219. * @function
  5220. * @param {Node | number} x - The parameter.
  5221. * @returns {Node}
  5222. */
  5223. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  5224. /**
  5225. * Returns the inverse hyperbolic sine of the parameter.
  5226. *
  5227. * @tsl
  5228. * @function
  5229. * @param {Node | number} x - The parameter.
  5230. * @returns {Node}
  5231. */
  5232. const asinh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASINH ).setParameterLength( 1 );
  5233. /**
  5234. * Returns the arccosine of the parameter.
  5235. *
  5236. * @tsl
  5237. * @function
  5238. * @param {Node | number} x - The parameter.
  5239. * @returns {Node}
  5240. */
  5241. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  5242. /**
  5243. * Returns the inverse hyperbolic cosine of the parameter.
  5244. *
  5245. * @tsl
  5246. * @function
  5247. * @param {Node | number} x - The parameter.
  5248. * @returns {Node}
  5249. */
  5250. const acosh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOSH ).setParameterLength( 1 );
  5251. /**
  5252. * Returns the arc-tangent of the parameter.
  5253. * If two parameters are provided, the result is `atan2(y/x)`.
  5254. *
  5255. * @tsl
  5256. * @function
  5257. * @param {Node | number} y - The y parameter.
  5258. * @param {?(Node | number)} x - The x parameter.
  5259. * @returns {Node}
  5260. */
  5261. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  5262. /**
  5263. * Returns the inverse hyperbolic tangent of the parameter.
  5264. *
  5265. * @tsl
  5266. * @function
  5267. * @param {Node | number} x - The parameter.
  5268. * @returns {Node}
  5269. */
  5270. const atanh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATANH ).setParameterLength( 1 );
  5271. /**
  5272. * Returns the absolute value of the parameter.
  5273. *
  5274. * @tsl
  5275. * @function
  5276. * @param {Node | number} x - The parameter.
  5277. * @returns {Node}
  5278. */
  5279. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  5280. /**
  5281. * Extracts the sign of the parameter.
  5282. *
  5283. * @tsl
  5284. * @function
  5285. * @param {Node | number} x - The parameter.
  5286. * @returns {Node}
  5287. */
  5288. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  5289. /**
  5290. * Calculates the length of a vector.
  5291. *
  5292. * @tsl
  5293. * @function
  5294. * @param {Node} x - The parameter.
  5295. * @returns {Node<float>}
  5296. */
  5297. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  5298. /**
  5299. * Negates the value of the parameter (-x).
  5300. *
  5301. * @tsl
  5302. * @function
  5303. * @param {Node | number} x - The parameter.
  5304. * @returns {Node}
  5305. */
  5306. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  5307. /**
  5308. * Return `1` minus the parameter.
  5309. *
  5310. * @tsl
  5311. * @function
  5312. * @param {Node | number} x - The parameter.
  5313. * @returns {Node}
  5314. */
  5315. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  5316. /**
  5317. * Returns the partial derivative of the parameter with respect to x.
  5318. *
  5319. * @tsl
  5320. * @function
  5321. * @param {Node | number} x - The parameter.
  5322. * @returns {Node}
  5323. */
  5324. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  5325. /**
  5326. * Returns the partial derivative of the parameter with respect to y.
  5327. *
  5328. * @tsl
  5329. * @function
  5330. * @param {Node | number} x - The parameter.
  5331. * @returns {Node}
  5332. */
  5333. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  5334. /**
  5335. * Rounds the parameter to the nearest integer.
  5336. *
  5337. * @tsl
  5338. * @function
  5339. * @param {Node | number} x - The parameter.
  5340. * @returns {Node}
  5341. */
  5342. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  5343. /**
  5344. * Returns the reciprocal of the parameter `(1/x)`.
  5345. *
  5346. * @tsl
  5347. * @function
  5348. * @param {Node | number} x - The parameter.
  5349. * @returns {Node}
  5350. */
  5351. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  5352. /**
  5353. * Truncates the parameter, removing the fractional part.
  5354. *
  5355. * @tsl
  5356. * @function
  5357. * @param {Node | number} x - The parameter.
  5358. * @returns {Node}
  5359. */
  5360. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  5361. /**
  5362. * Returns the sum of the absolute derivatives in x and y.
  5363. *
  5364. * @tsl
  5365. * @function
  5366. * @param {Node | number} x - The parameter.
  5367. * @returns {Node}
  5368. */
  5369. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  5370. /**
  5371. * Returns the transpose of a matrix.
  5372. *
  5373. * @tsl
  5374. * @function
  5375. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  5376. * @returns {Node}
  5377. */
  5378. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  5379. /**
  5380. * Returns the determinant of a matrix.
  5381. *
  5382. * @tsl
  5383. * @function
  5384. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  5385. * @returns {Node<float>}
  5386. */
  5387. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  5388. /**
  5389. * Returns the inverse of a matrix.
  5390. *
  5391. * @tsl
  5392. * @function
  5393. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  5394. * @returns {Node<mat2|mat3|mat4>}
  5395. */
  5396. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  5397. // 2 inputs
  5398. /**
  5399. * Returns the least of the given values.
  5400. *
  5401. * @tsl
  5402. * @function
  5403. * @param {...(Node | number)} values - The values to compare.
  5404. * @returns {Node}
  5405. */
  5406. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  5407. /**
  5408. * Returns the greatest of the given values.
  5409. *
  5410. * @tsl
  5411. * @function
  5412. * @param {...(Node | number)} values - The values to compare.
  5413. * @returns {Node}
  5414. */
  5415. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  5416. /**
  5417. * Generate a step function by comparing two values.
  5418. *
  5419. * @tsl
  5420. * @function
  5421. * @param {Node | number} x - The y parameter.
  5422. * @param {Node | number} y - The x parameter.
  5423. * @returns {Node}
  5424. */
  5425. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  5426. /**
  5427. * Calculates the reflection direction for an incident vector.
  5428. *
  5429. * @tsl
  5430. * @function
  5431. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5432. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5433. * @returns {Node<vec2|vec3|vec4>}
  5434. */
  5435. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  5436. /**
  5437. * Calculates the distance between two points.
  5438. *
  5439. * @tsl
  5440. * @function
  5441. * @param {Node<vec2|vec3|vec4>} x - The first point.
  5442. * @param {Node<vec2|vec3|vec4>} y - The second point.
  5443. * @returns {Node<float>}
  5444. */
  5445. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  5446. /**
  5447. * Calculates the absolute difference between two values.
  5448. *
  5449. * @tsl
  5450. * @function
  5451. * @param {Node | number} x - The first parameter.
  5452. * @param {Node | number} y - The second parameter.
  5453. * @returns {Node}
  5454. */
  5455. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  5456. /**
  5457. * Calculates the dot product of two vectors.
  5458. *
  5459. * @tsl
  5460. * @function
  5461. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  5462. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  5463. * @returns {Node<float>}
  5464. */
  5465. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  5466. /**
  5467. * Calculates the cross product of two vectors.
  5468. *
  5469. * @tsl
  5470. * @function
  5471. * @param {Node<vec2|vec3>} x - The first vector.
  5472. * @param {Node<vec2|vec3>} y - The second vector.
  5473. * @returns {Node<float|vec3>}
  5474. */
  5475. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  5476. /**
  5477. * Return the value of the first parameter raised to the power of the second one.
  5478. *
  5479. * @tsl
  5480. * @function
  5481. * @param {Node | number} x - The first parameter.
  5482. * @param {Node | number} y - The second parameter.
  5483. * @returns {Node}
  5484. */
  5485. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  5486. /**
  5487. * Returns the square of the parameter.
  5488. *
  5489. * @tsl
  5490. * @function
  5491. * @param {Node | number} x - The first parameter.
  5492. * @returns {Node}
  5493. */
  5494. const pow2 = ( x ) => mul( x, x );
  5495. /**
  5496. * Returns the cube of the parameter.
  5497. *
  5498. * @tsl
  5499. * @function
  5500. * @param {Node | number} x - The first parameter.
  5501. * @returns {Node}
  5502. */
  5503. const pow3 = ( x ) => mul( x, x, x );
  5504. /**
  5505. * Returns the fourth power of the parameter.
  5506. *
  5507. * @tsl
  5508. * @function
  5509. * @param {Node | number} x - The first parameter.
  5510. * @returns {Node}
  5511. */
  5512. const pow4 = ( x ) => mul( x, x, x, x );
  5513. /**
  5514. * Transforms the direction of a vector by a matrix and then normalizes the result.
  5515. *
  5516. * @tsl
  5517. * @function
  5518. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  5519. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  5520. * @returns {Node}
  5521. */
  5522. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  5523. /**
  5524. * Transforms a normal vector by the view matrix and then normalizes the result.
  5525. *
  5526. * The upper-left 3x3 of the view matrix is assumed to be orthonormal, so the
  5527. * normal can be transformed directly without involving the normal matrix.
  5528. *
  5529. * @tsl
  5530. * @function
  5531. * @param {Node<vec3>} normal - The normal vector, given in world space.
  5532. * @param {Node<mat3|mat4>} viewMatrix - The view matrix.
  5533. * @returns {Node<vec3>} The normal vector in view space.
  5534. */
  5535. const transformNormalByViewMatrix = ( normal, viewMatrix ) => normalize( mul( viewMatrix, vec4( vec3( normal ), 0.0 ) ).xyz );
  5536. /**
  5537. * Transforms a normal vector by the inverse of the view matrix and then normalizes the result.
  5538. *
  5539. * The upper-left 3x3 of the view matrix is assumed to be orthonormal, so post-multiplying
  5540. * by the view matrix is equivalent to pre-multiplying by its inverse.
  5541. *
  5542. * @tsl
  5543. * @function
  5544. * @param {Node<vec3>} normal - The normal vector, given in view space.
  5545. * @param {Node<mat3|mat4>} viewMatrix - The view matrix.
  5546. * @returns {Node<vec3>} The normal vector in world space.
  5547. */
  5548. const transformNormalByInverseViewMatrix = ( normal, viewMatrix ) => normalize( vec4( vec3( normal ), 0.0 ).mul( viewMatrix ).xyz );
  5549. /**
  5550. * Returns the cube root of a number.
  5551. *
  5552. * @tsl
  5553. * @function
  5554. * @param {Node | number} a - The first parameter.
  5555. * @returns {Node}
  5556. */
  5557. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  5558. /**
  5559. * Calculate the squared length of a vector.
  5560. *
  5561. * @tsl
  5562. * @function
  5563. * @param {Node<vec2|vec3|vec4>} a - The vector.
  5564. * @returns {Node<float>}
  5565. */
  5566. const lengthSq = ( a ) => dot( a, a );
  5567. /**
  5568. * Linearly interpolates between two values.
  5569. *
  5570. * @tsl
  5571. * @function
  5572. * @param {Node | number} a - The first parameter.
  5573. * @param {Node | number} b - The second parameter.
  5574. * @param {Node | number} t - The interpolation value.
  5575. * @returns {Node}
  5576. */
  5577. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  5578. /**
  5579. * Constrains a value to lie between two further values.
  5580. *
  5581. * @tsl
  5582. * @function
  5583. * @param {Node | number} value - The value to constrain.
  5584. * @param {Node | number} [low=0] - The lower bound.
  5585. * @param {Node | number} [high=1] - The upper bound.
  5586. * @returns {Node}
  5587. */
  5588. const clamp = ( value, low = 0, high = 1 ) => new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) );
  5589. /**
  5590. * Constrains a value between `0` and `1`.
  5591. *
  5592. * @tsl
  5593. * @function
  5594. * @param {Node | number} value - The value to constrain.
  5595. * @returns {Node}
  5596. */
  5597. const saturate = ( value ) => clamp( value );
  5598. /**
  5599. * Calculates the refraction direction for an incident vector.
  5600. *
  5601. * @tsl
  5602. * @function
  5603. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5604. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5605. * @param {Node<float>} eta - The ratio of indices of refraction.
  5606. * @returns {Node<vec2|vec3|vec4>}
  5607. */
  5608. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  5609. /**
  5610. * Performs a Hermite interpolation between two values.
  5611. *
  5612. * @tsl
  5613. * @function
  5614. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5615. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5616. * @param {Node | number} x - The source value for interpolation.
  5617. * @returns {Node}
  5618. */
  5619. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  5620. /**
  5621. * Returns a vector pointing in the same direction as another.
  5622. *
  5623. * @tsl
  5624. * @function
  5625. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  5626. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5627. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  5628. * @returns {Node<vec2|vec3|vec4>}
  5629. */
  5630. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  5631. /**
  5632. * Returns a random value for the given uv.
  5633. *
  5634. * @tsl
  5635. * @function
  5636. * @param {Node<vec2>} uv - The uv node.
  5637. * @returns {Node<float>}
  5638. */
  5639. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  5640. const a = 12.9898, b = 78.233, c = 43758.5453;
  5641. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  5642. return fract( sin( sn ).mul( c ) );
  5643. } );
  5644. /**
  5645. * Alias for `mix()` with a different parameter order.
  5646. *
  5647. * @tsl
  5648. * @function
  5649. * @param {Node | number} t - The interpolation value.
  5650. * @param {Node | number} e1 - The first parameter.
  5651. * @param {Node | number} e2 - The second parameter.
  5652. * @returns {Node}
  5653. */
  5654. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5655. /**
  5656. * Alias for `smoothstep()` with a different parameter order.
  5657. *
  5658. * @tsl
  5659. * @function
  5660. * @param {Node | number} x - The source value for interpolation.
  5661. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5662. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5663. * @returns {Node}
  5664. */
  5665. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5666. /**
  5667. * Alias for `step()` with a different parameter order.
  5668. *
  5669. * @tsl
  5670. * @function
  5671. * @param {Node | number} x - The source value for interpolation.
  5672. * @param {Node | number} edge - The edge value.
  5673. * @returns {Node}
  5674. */
  5675. const stepElement = ( x, edge ) => step( edge, x );
  5676. // GLSL alias function
  5677. const faceforward = faceForward;
  5678. const inversesqrt = inverseSqrt;
  5679. // Method chaining
  5680. addMethodChaining( 'all', all );
  5681. addMethodChaining( 'any', any );
  5682. addMethodChaining( 'radians', radians );
  5683. addMethodChaining( 'degrees', degrees );
  5684. addMethodChaining( 'exp', exp );
  5685. addMethodChaining( 'exp2', exp2 );
  5686. addMethodChaining( 'log', log );
  5687. addMethodChaining( 'log2', log2 );
  5688. addMethodChaining( 'sqrt', sqrt );
  5689. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5690. addMethodChaining( 'floor', floor );
  5691. addMethodChaining( 'ceil', ceil );
  5692. addMethodChaining( 'normalize', normalize );
  5693. addMethodChaining( 'fract', fract );
  5694. addMethodChaining( 'sin', sin );
  5695. addMethodChaining( 'sinh', sinh );
  5696. addMethodChaining( 'cos', cos );
  5697. addMethodChaining( 'cosh', cosh );
  5698. addMethodChaining( 'tan', tan );
  5699. addMethodChaining( 'tanh', tanh );
  5700. addMethodChaining( 'asin', asin );
  5701. addMethodChaining( 'asinh', asinh );
  5702. addMethodChaining( 'acos', acos );
  5703. addMethodChaining( 'acosh', acosh );
  5704. addMethodChaining( 'atan', atan );
  5705. addMethodChaining( 'atanh', atanh );
  5706. addMethodChaining( 'abs', abs );
  5707. addMethodChaining( 'sign', sign );
  5708. addMethodChaining( 'length', length );
  5709. addMethodChaining( 'lengthSq', lengthSq );
  5710. addMethodChaining( 'negate', negate );
  5711. addMethodChaining( 'oneMinus', oneMinus );
  5712. addMethodChaining( 'dFdx', dFdx );
  5713. addMethodChaining( 'dFdy', dFdy );
  5714. addMethodChaining( 'round', round );
  5715. addMethodChaining( 'reciprocal', reciprocal );
  5716. addMethodChaining( 'trunc', trunc );
  5717. addMethodChaining( 'fwidth', fwidth );
  5718. addMethodChaining( 'min', min$1 );
  5719. addMethodChaining( 'max', max$1 );
  5720. addMethodChaining( 'step', stepElement );
  5721. addMethodChaining( 'reflect', reflect );
  5722. addMethodChaining( 'distance', distance );
  5723. addMethodChaining( 'dot', dot );
  5724. addMethodChaining( 'cross', cross );
  5725. addMethodChaining( 'pow', pow );
  5726. addMethodChaining( 'pow2', pow2 );
  5727. addMethodChaining( 'pow3', pow3 );
  5728. addMethodChaining( 'pow4', pow4 );
  5729. addMethodChaining( 'transformDirection', transformDirection );
  5730. addMethodChaining( 'transformNormalByViewMatrix', transformNormalByViewMatrix );
  5731. addMethodChaining( 'transformNormalByInverseViewMatrix', transformNormalByInverseViewMatrix );
  5732. addMethodChaining( 'mix', mixElement );
  5733. addMethodChaining( 'clamp', clamp );
  5734. addMethodChaining( 'refract', refract );
  5735. addMethodChaining( 'smoothstep', smoothstepElement );
  5736. addMethodChaining( 'faceForward', faceForward );
  5737. addMethodChaining( 'difference', difference );
  5738. addMethodChaining( 'saturate', saturate );
  5739. addMethodChaining( 'cbrt', cbrt );
  5740. addMethodChaining( 'transpose', transpose );
  5741. addMethodChaining( 'determinant', determinant );
  5742. addMethodChaining( 'inverse', inverse );
  5743. addMethodChaining( 'rand', rand );
  5744. /**
  5745. * Represents a logical `if/else` statement. Can be used as an alternative
  5746. * to the `If()`/`Else()` syntax.
  5747. *
  5748. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5749. * determine the outcome of the entire statement.
  5750. *
  5751. * ```js
  5752. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5753. * ```
  5754. *
  5755. * @augments Node
  5756. */
  5757. class ConditionalNode extends Node {
  5758. static get type() {
  5759. return 'ConditionalNode';
  5760. }
  5761. /**
  5762. * Constructs a new conditional node.
  5763. *
  5764. * @param {Node} condNode - The node that defines the condition.
  5765. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5766. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5767. */
  5768. constructor( condNode, ifNode, elseNode = null ) {
  5769. super();
  5770. /**
  5771. * The node that defines the condition.
  5772. *
  5773. * @type {Node}
  5774. */
  5775. this.condNode = condNode;
  5776. /**
  5777. * The node that is evaluate when the condition ends up `true`.
  5778. *
  5779. * @type {Node}
  5780. */
  5781. this.ifNode = ifNode;
  5782. /**
  5783. * The node that is evaluate when the condition ends up `false`.
  5784. *
  5785. * @type {?Node}
  5786. * @default null
  5787. */
  5788. this.elseNode = elseNode;
  5789. }
  5790. /**
  5791. * This method is overwritten since the node type is inferred from the if/else
  5792. * nodes.
  5793. *
  5794. * @param {NodeBuilder} builder - The current node builder.
  5795. * @return {string} The node type.
  5796. */
  5797. generateNodeType( builder ) {
  5798. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5799. if ( ifNode === undefined ) {
  5800. // fallback setup
  5801. builder.flowBuildStage( this, 'setup' );
  5802. return this.getNodeType( builder );
  5803. }
  5804. const ifType = ifNode.getNodeType( builder );
  5805. if ( elseNode !== null ) {
  5806. const elseType = elseNode.getNodeType( builder );
  5807. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5808. return elseType;
  5809. }
  5810. }
  5811. return ifType;
  5812. }
  5813. setup( builder ) {
  5814. const condNode = this.condNode;
  5815. const ifNode = this.ifNode.isolate();
  5816. const elseNode = this.elseNode ? this.elseNode.isolate() : null;
  5817. //
  5818. const currentNodeBlock = builder.context.nodeBlock;
  5819. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5820. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5821. //
  5822. const isUniformFlow = builder.context.uniformFlow;
  5823. const properties = builder.getNodeProperties( this );
  5824. properties.condNode = condNode;
  5825. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5826. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5827. }
  5828. generate( builder, output ) {
  5829. const type = this.getNodeType( builder );
  5830. const nodeData = builder.getDataFromNode( this );
  5831. if ( nodeData.nodeProperty !== undefined ) {
  5832. return nodeData.nodeProperty;
  5833. }
  5834. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5835. const functionNode = builder.currentFunctionNode;
  5836. const needsOutput = output !== 'void';
  5837. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5838. nodeData.nodeProperty = nodeProperty;
  5839. const nodeSnippet = condNode.build( builder, 'bool' );
  5840. const isUniformFlow = builder.context.uniformFlow;
  5841. if ( isUniformFlow && elseNode !== null ) {
  5842. const ifSnippet = ifNode.build( builder, type );
  5843. const elseSnippet = elseNode.build( builder, type );
  5844. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5845. // TODO: If node property already exists return something else
  5846. return builder.format( mathSnippet, type, output );
  5847. }
  5848. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5849. let ifSnippet = ifNode.build( builder, type );
  5850. if ( ifSnippet ) {
  5851. if ( needsOutput ) {
  5852. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5853. } else {
  5854. ifSnippet = 'return ' + ifSnippet + ';';
  5855. if ( functionNode === null ) {
  5856. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.', this.stackTrace );
  5857. ifSnippet = '// ' + ifSnippet;
  5858. }
  5859. }
  5860. }
  5861. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5862. if ( elseNode !== null ) {
  5863. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5864. let elseSnippet = elseNode.build( builder, type );
  5865. if ( elseSnippet ) {
  5866. if ( needsOutput ) {
  5867. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5868. } else {
  5869. elseSnippet = 'return ' + elseSnippet + ';';
  5870. if ( functionNode === null ) {
  5871. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.', this.stackTrace );
  5872. elseSnippet = '// ' + elseSnippet;
  5873. }
  5874. }
  5875. }
  5876. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5877. } else {
  5878. builder.addFlowCode( '\n\n' );
  5879. }
  5880. return builder.format( nodeProperty, type, output );
  5881. }
  5882. }
  5883. /**
  5884. * TSL function for creating a conditional node.
  5885. *
  5886. * @tsl
  5887. * @function
  5888. * @param {Node} condNode - The node that defines the condition.
  5889. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5890. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5891. * @returns {ConditionalNode}
  5892. */
  5893. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5894. addMethodChaining( 'select', select );
  5895. /**
  5896. * This node can be used as a context management component for another node.
  5897. * {@link NodeBuilder} performs its node building process in a specific context and
  5898. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5899. *
  5900. * ```js
  5901. *node.context( { getUV: () => customCoord } );
  5902. *\// or
  5903. *material.contextNode = context( { getUV: () => customCoord } );
  5904. *\// or
  5905. *renderer.contextNode = context( { getUV: () => customCoord } );
  5906. *\// or
  5907. *scenePass.contextNode = context( { getUV: () => customCoord } );
  5908. *```
  5909. * @augments Node
  5910. */
  5911. class ContextNode extends Node {
  5912. static get type() {
  5913. return 'ContextNode';
  5914. }
  5915. /**
  5916. * Constructs a new context node.
  5917. *
  5918. * @param {Node} node - The node whose context should be modified.
  5919. * @param {Object} [value={}] - The modified context data.
  5920. */
  5921. constructor( node = null, value = {} ) {
  5922. super();
  5923. /**
  5924. * This flag can be used for type testing.
  5925. *
  5926. * @type {boolean}
  5927. * @readonly
  5928. * @default true
  5929. */
  5930. this.isContextNode = true;
  5931. /**
  5932. * The node whose context should be modified.
  5933. *
  5934. * @type {Node}
  5935. */
  5936. this.node = node;
  5937. /**
  5938. * The modified context data.
  5939. *
  5940. * @type {Object}
  5941. * @default {}
  5942. */
  5943. this.value = value;
  5944. }
  5945. /**
  5946. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5947. *
  5948. * @return {Node} A reference to {@link ContextNode#node}.
  5949. */
  5950. getScope() {
  5951. return this.node.getScope();
  5952. }
  5953. /**
  5954. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5955. *
  5956. * @param {NodeBuilder} builder - The current node builder.
  5957. * @return {string} The node type.
  5958. */
  5959. generateNodeType( builder ) {
  5960. return this.node.getNodeType( builder );
  5961. }
  5962. /**
  5963. * Gathers the context data from all parent context nodes.
  5964. *
  5965. * @return {Object} The gathered context data.
  5966. */
  5967. getFlowContextData() {
  5968. const children = [];
  5969. this.traverse( ( node ) => {
  5970. if ( node.isContextNode === true ) {
  5971. children.push( node.value );
  5972. }
  5973. } );
  5974. return Object.assign( {}, ...children );
  5975. }
  5976. /**
  5977. * This method is overwritten to ensure it returns the member type of {@link ContextNode#node}.
  5978. *
  5979. * @param {NodeBuilder} builder - The current node builder.
  5980. * @param {string} name - The member name.
  5981. * @returns {string} The member type.
  5982. */
  5983. getMemberType( builder, name ) {
  5984. return this.node.getMemberType( builder, name );
  5985. }
  5986. analyze( builder ) {
  5987. const previousContext = builder.addContext( this.value );
  5988. this.node.build( builder );
  5989. builder.setContext( previousContext );
  5990. }
  5991. setup( builder ) {
  5992. const previousContext = builder.addContext( this.value );
  5993. this.node.build( builder );
  5994. builder.setContext( previousContext );
  5995. }
  5996. generate( builder, output ) {
  5997. const previousContext = builder.addContext( this.value );
  5998. const snippet = this.node.build( builder, output );
  5999. builder.setContext( previousContext );
  6000. return snippet;
  6001. }
  6002. }
  6003. /**
  6004. * TSL function for creating a context node.
  6005. *
  6006. * @tsl
  6007. * @function
  6008. * @param {Node|Object} [nodeOrValue={}] - The node whose context should be modified or the modified context data.
  6009. * @param {Object} [value={}] - The modified context data.
  6010. * @returns {ContextNode}
  6011. */
  6012. const context = ( nodeOrValue = null, value = {} ) => {
  6013. let node = nodeOrValue;
  6014. if ( node === null || node.isNode !== true ) {
  6015. value = node || value;
  6016. node = null;
  6017. }
  6018. return new ContextNode( node, value );
  6019. };
  6020. /**
  6021. * TSL function for defining a uniformFlow context value for a given node.
  6022. *
  6023. * @tsl
  6024. * @function
  6025. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  6026. * @returns {ContextNode}
  6027. */
  6028. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  6029. /**
  6030. * TSL function for defining a name for the context value for a given node.
  6031. *
  6032. * @tsl
  6033. * @function
  6034. * @param {Node} node - The node whose context should be modified.
  6035. * @param {string} name - The name to set.
  6036. * @returns {ContextNode}
  6037. */
  6038. const setName = ( node, name ) => context( node, { nodeName: name } );
  6039. /**
  6040. * TSL function for defining a built-in shadow context for a given node.
  6041. *
  6042. * @tsl
  6043. * @function
  6044. * @param {ShadowNode} shadowNode - The shadow node representing the light's shadow.
  6045. * @param {Light} light - The light associated with the shadow.
  6046. * @param {Node} [node=null] - The node whose context should be modified.
  6047. * @returns {ContextNode}
  6048. */
  6049. function builtinShadowContext( shadowNode, light, node = null ) {
  6050. return context( node, {
  6051. getShadow: ( { light: shadowLight, shadowColorNode } ) => {
  6052. if ( light === shadowLight ) {
  6053. return shadowColorNode.mul( shadowNode );
  6054. }
  6055. return shadowColorNode;
  6056. }
  6057. } );
  6058. }
  6059. /**
  6060. * TSL function for defining a built-in ambient occlusion context for a given node.
  6061. *
  6062. * @tsl
  6063. * @function
  6064. * @param {Node} aoNode - The ambient occlusion value node to apply.
  6065. * @param {Node} [node=null] - The node whose context should be modified.
  6066. * @returns {ContextNode}
  6067. */
  6068. function builtinAOContext( aoNode, node = null ) {
  6069. return context( node, {
  6070. getAO: ( inputNode, { material } ) => {
  6071. if ( material.transparent === true ) return inputNode;
  6072. return inputNode !== null ? inputNode.mul( aoNode ) : aoNode;
  6073. }
  6074. } );
  6075. }
  6076. /**
  6077. * TSL function for defining a label context value for a given node.
  6078. *
  6079. * @tsl
  6080. * @function
  6081. * @deprecated
  6082. * @param {Node} node - The node whose context should be modified.
  6083. * @param {string} name - The name/label to set.
  6084. * @returns {ContextNode}
  6085. */
  6086. function label( node, name ) {
  6087. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  6088. return setName( node, name );
  6089. }
  6090. addMethodChaining( 'context', context );
  6091. addMethodChaining( 'label', label );
  6092. addMethodChaining( 'uniformFlow', uniformFlow );
  6093. addMethodChaining( 'setName', setName );
  6094. addMethodChaining( 'builtinShadowContext', ( node, shadowNode, light ) => builtinShadowContext( shadowNode, light, node ) );
  6095. addMethodChaining( 'builtinAOContext', ( node, aoValue ) => builtinAOContext( aoValue, node ) );
  6096. /**
  6097. * Class for representing shader variables as nodes. Variables are created from
  6098. * existing nodes like the following:
  6099. *
  6100. * ```js
  6101. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  6102. * ```
  6103. *
  6104. * @augments Node
  6105. */
  6106. class VarNode extends Node {
  6107. static get type() {
  6108. return 'VarNode';
  6109. }
  6110. /**
  6111. * Constructs a new variable node.
  6112. *
  6113. * @param {Node} node - The node for which a variable should be created.
  6114. * @param {?string} [name=null] - The name of the variable in the shader.
  6115. * @param {boolean} [readOnly=false] - The read-only flag.
  6116. */
  6117. constructor( node, name = null, readOnly = false ) {
  6118. super();
  6119. /**
  6120. * The node for which a variable should be created.
  6121. *
  6122. * @type {Node}
  6123. */
  6124. this.node = node;
  6125. /**
  6126. * The name of the variable in the shader. If no name is defined,
  6127. * the node system auto-generates one.
  6128. *
  6129. * @type {?string}
  6130. * @default null
  6131. */
  6132. this.name = name;
  6133. /**
  6134. * `VarNode` sets this property to `true` by default.
  6135. *
  6136. * @type {boolean}
  6137. * @default true
  6138. */
  6139. this.global = true;
  6140. /**
  6141. * This flag can be used for type testing.
  6142. *
  6143. * @type {boolean}
  6144. * @readonly
  6145. * @default true
  6146. */
  6147. this.isVarNode = true;
  6148. /**
  6149. *
  6150. * The read-only flag.
  6151. *
  6152. * @type {boolean}
  6153. * @default false
  6154. */
  6155. this.readOnly = readOnly;
  6156. /**
  6157. *
  6158. * Add this flag to the node system to indicate that this node require parents.
  6159. *
  6160. * @type {boolean}
  6161. * @default true
  6162. */
  6163. this.parents = true;
  6164. /**
  6165. * This flag is used to indicate that this node is used for intent.
  6166. *
  6167. * @type {boolean}
  6168. * @default false
  6169. */
  6170. this.intent = false;
  6171. }
  6172. /**
  6173. * Sets the intent flag for this node.
  6174. *
  6175. * This flag is used to indicate that this node is used for intent
  6176. * and should not be built directly. Instead, it is used to indicate that
  6177. * the node should be treated as a variable intent.
  6178. *
  6179. * It's useful for assigning variables without needing creating a new variable node.
  6180. *
  6181. * @param {boolean} value - The value to set for the intent flag.
  6182. * @returns {VarNode} This node.
  6183. */
  6184. setIntent( value ) {
  6185. this.intent = value;
  6186. return this;
  6187. }
  6188. /**
  6189. * Checks if this node is used for intent.
  6190. *
  6191. * @param {NodeBuilder} builder - The node builder.
  6192. * @returns {boolean} Whether this node is used for intent.
  6193. */
  6194. isIntent( builder ) {
  6195. const data = builder.getDataFromNode( this );
  6196. if ( data.forceDeclaration === true ) return false;
  6197. return this.intent;
  6198. }
  6199. /**
  6200. * Returns the intent flag of this node.
  6201. *
  6202. * @return {boolean} The intent flag.
  6203. */
  6204. getIntent() {
  6205. return this.intent;
  6206. }
  6207. getMemberType( builder, name ) {
  6208. return this.node.getMemberType( builder, name );
  6209. }
  6210. getElementType( builder ) {
  6211. return this.node.getElementType( builder );
  6212. }
  6213. generateNodeType( builder ) {
  6214. return this.node.getNodeType( builder );
  6215. }
  6216. getArrayCount( builder ) {
  6217. return this.node.getArrayCount( builder );
  6218. }
  6219. isAssign( builder ) {
  6220. const data = builder.getDataFromNode( this );
  6221. return data.assign;
  6222. }
  6223. build( ...params ) {
  6224. const builder = params[ 0 ];
  6225. const refNode = this.getShared( builder );
  6226. if ( this !== refNode ) {
  6227. return refNode.build( ...params );
  6228. }
  6229. if ( this._hasStack( builder ) === false && builder.buildStage === 'setup' ) {
  6230. if ( builder.context.nodeLoop || builder.context.nodeBlock ) {
  6231. let addBefore = false;
  6232. if ( this.node.isShaderCallNodeInternal && this.node.shaderNode.getLayout() === null ) {
  6233. if ( builder.fnCall && builder.fnCall.shaderNode ) {
  6234. const shaderNodeData = builder.getDataFromNode( this.node.shaderNode );
  6235. if ( shaderNodeData.hasLoop ) {
  6236. const data = builder.getDataFromNode( this );
  6237. data.forceDeclaration = true;
  6238. addBefore = true;
  6239. }
  6240. }
  6241. }
  6242. const baseStack = builder.getBaseStack();
  6243. if ( addBefore ) {
  6244. baseStack.addToStackBefore( this );
  6245. } else {
  6246. baseStack.addToStack( this );
  6247. }
  6248. }
  6249. }
  6250. if ( this.isIntent( builder ) ) {
  6251. if ( this.isAssign( builder ) !== true ) {
  6252. return this.node.build( ...params );
  6253. }
  6254. }
  6255. return super.build( ...params );
  6256. }
  6257. generate( builder ) {
  6258. const { node, name, readOnly } = this;
  6259. const { renderer } = builder;
  6260. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  6261. let isDeterministic = false;
  6262. let shouldTreatAsReadOnly = false;
  6263. if ( readOnly ) {
  6264. isDeterministic = builder.isDeterministic( node );
  6265. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  6266. }
  6267. const nodeType = this.getNodeType( builder );
  6268. if ( nodeType == 'void' ) {
  6269. if ( this.isIntent( builder ) !== true ) {
  6270. error( 'TSL: ".toVar()" can not be used with void type.', this.stackTrace );
  6271. }
  6272. const snippet = node.build( builder );
  6273. return snippet;
  6274. }
  6275. const vectorType = builder.getVectorType( nodeType );
  6276. const snippet = node.build( builder, vectorType );
  6277. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  6278. const propertyName = builder.getPropertyName( nodeVar );
  6279. let declarationPrefix = propertyName;
  6280. if ( shouldTreatAsReadOnly ) {
  6281. if ( isWebGPUBackend ) {
  6282. declarationPrefix = isDeterministic
  6283. ? `const ${ propertyName }`
  6284. : `let ${ propertyName }`;
  6285. } else {
  6286. const count = node.getArrayCount( builder );
  6287. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  6288. }
  6289. }
  6290. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  6291. return propertyName;
  6292. }
  6293. _hasStack( builder ) {
  6294. const nodeData = builder.getDataFromNode( this );
  6295. return nodeData.stack !== undefined;
  6296. }
  6297. }
  6298. /**
  6299. * TSL function for creating a var node.
  6300. *
  6301. * @tsl
  6302. * @function
  6303. * @param {Node} node - The node for which a variable should be created.
  6304. * @param {?string} name - The name of the variable in the shader.
  6305. * @returns {VarNode}
  6306. */
  6307. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  6308. /**
  6309. * TSL function for creating a var node.
  6310. *
  6311. * @tsl
  6312. * @function
  6313. * @param {Node} node - The node for which a variable should be created.
  6314. * @param {?string} name - The name of the variable in the shader.
  6315. * @returns {VarNode}
  6316. */
  6317. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  6318. /**
  6319. * TSL function for creating a const node.
  6320. *
  6321. * @tsl
  6322. * @function
  6323. * @param {Node} node - The node for which a constant should be created.
  6324. * @param {?string} name - The name of the constant in the shader.
  6325. * @returns {VarNode}
  6326. */
  6327. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  6328. //
  6329. //
  6330. /**
  6331. * TSL function for creating a var intent node.
  6332. *
  6333. * @tsl
  6334. * @function
  6335. * @param {Node} node - The node for which a variable should be created.
  6336. * @param {?string} name - The name of the variable in the shader.
  6337. * @returns {VarNode}
  6338. */
  6339. const VarIntent = ( node ) => {
  6340. return createVar( node ).setIntent( true ).toStack();
  6341. };
  6342. // Method chaining
  6343. addMethodChaining( 'toVar', Var );
  6344. addMethodChaining( 'toConst', Const );
  6345. addMethodChaining( 'toVarIntent', VarIntent );
  6346. /**
  6347. * This node is used to build a sub-build in the node system.
  6348. *
  6349. * @augments Node
  6350. * @param {Node} node - The node to be built in the sub-build.
  6351. * @param {string} name - The name of the sub-build.
  6352. * @param {?string} [nodeType=null] - The type of the node, if known.
  6353. */
  6354. class SubBuildNode extends Node {
  6355. static get type() {
  6356. return 'SubBuild';
  6357. }
  6358. constructor( node, name, nodeType = null ) {
  6359. super( nodeType );
  6360. /**
  6361. * The node to be built in the sub-build.
  6362. *
  6363. * @type {Node}
  6364. */
  6365. this.node = node;
  6366. /**
  6367. * The name of the sub-build.
  6368. *
  6369. * @type {string}
  6370. */
  6371. this.name = name;
  6372. /**
  6373. * This flag can be used for type testing.
  6374. *
  6375. * @type {boolean}
  6376. * @readonly
  6377. * @default true
  6378. */
  6379. this.isSubBuildNode = true;
  6380. }
  6381. generateNodeType( builder ) {
  6382. if ( this.nodeType !== null ) return this.nodeType;
  6383. builder.addSubBuild( this.name );
  6384. const nodeType = this.node.getNodeType( builder );
  6385. builder.removeSubBuild();
  6386. return nodeType;
  6387. }
  6388. build( builder, ...params ) {
  6389. builder.addSubBuild( this.name );
  6390. const data = this.node.build( builder, ...params );
  6391. builder.removeSubBuild();
  6392. return data;
  6393. }
  6394. }
  6395. /**
  6396. * Creates a new sub-build node.
  6397. *
  6398. * @tsl
  6399. * @function
  6400. * @param {Node} node - The node to be built in the sub-build.
  6401. * @param {string} name - The name of the sub-build.
  6402. * @param {?string} [type=null] - The type of the node, if known.
  6403. * @returns {Node} A node object wrapping the SubBuildNode instance.
  6404. */
  6405. const subBuild = ( node, name, type = null ) => new SubBuildNode( nodeObject( node ), name, type );
  6406. /**
  6407. * Class for representing shader varyings as nodes. Varyings are create from
  6408. * existing nodes like the following:
  6409. *
  6410. * ```js
  6411. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  6412. * ```
  6413. *
  6414. * @augments Node
  6415. */
  6416. class VaryingNode extends Node {
  6417. static get type() {
  6418. return 'VaryingNode';
  6419. }
  6420. /**
  6421. * Constructs a new varying node.
  6422. *
  6423. * @param {Node} node - The node for which a varying should be created.
  6424. * @param {?string} name - The name of the varying in the shader.
  6425. */
  6426. constructor( node, name = null ) {
  6427. super();
  6428. /**
  6429. * The node for which a varying should be created.
  6430. *
  6431. * @type {Node}
  6432. */
  6433. this.node = subBuild( node, 'VERTEX' );
  6434. /**
  6435. * The name of the varying in the shader. If no name is defined,
  6436. * the node system auto-generates one.
  6437. *
  6438. * @type {?string}
  6439. * @default null
  6440. */
  6441. this.name = name;
  6442. /**
  6443. * This flag can be used for type testing.
  6444. *
  6445. * @type {boolean}
  6446. * @readonly
  6447. * @default true
  6448. */
  6449. this.isVaryingNode = true;
  6450. /**
  6451. * The interpolation type of the varying data.
  6452. *
  6453. * @type {?string}
  6454. * @default null
  6455. */
  6456. this.interpolationType = null;
  6457. /**
  6458. * The interpolation sampling type of varying data.
  6459. *
  6460. * @type {?string}
  6461. * @default null
  6462. */
  6463. this.interpolationSampling = null;
  6464. /**
  6465. * This flag is used for global cache.
  6466. *
  6467. * @type {boolean}
  6468. * @default true
  6469. */
  6470. this.global = true;
  6471. }
  6472. /**
  6473. * Defines the interpolation type of the varying.
  6474. *
  6475. * @param {string} type - The interpolation type.
  6476. * @param {?string} sampling - The interpolation sampling type
  6477. * @return {VaryingNode} A reference to this node.
  6478. */
  6479. setInterpolation( type, sampling = null ) {
  6480. this.interpolationType = type;
  6481. this.interpolationSampling = sampling;
  6482. return this;
  6483. }
  6484. getHash( builder ) {
  6485. return this.name || super.getHash( builder );
  6486. }
  6487. generateNodeType( builder ) {
  6488. // VaryingNode is auto type
  6489. return this.node.getNodeType( builder );
  6490. }
  6491. /**
  6492. * This method performs the setup of a varying node with the current node builder.
  6493. *
  6494. * @param {NodeBuilder} builder - The current node builder.
  6495. * @return {NodeVarying} The node varying from the node builder.
  6496. */
  6497. setupVarying( builder ) {
  6498. const properties = builder.getNodeProperties( this );
  6499. let varying = properties.varying;
  6500. if ( varying === undefined ) {
  6501. const name = this.name;
  6502. const type = this.getNodeType( builder );
  6503. const interpolationType = this.interpolationType;
  6504. const interpolationSampling = this.interpolationSampling;
  6505. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  6506. properties.node = subBuild( this.node, 'VERTEX' );
  6507. }
  6508. // this property can be used to check if the varying can be optimized for a variable
  6509. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  6510. return varying;
  6511. }
  6512. setup( builder ) {
  6513. this.setupVarying( builder );
  6514. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6515. }
  6516. analyze( builder ) {
  6517. this.setupVarying( builder );
  6518. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6519. }
  6520. generate( builder ) {
  6521. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  6522. const properties = builder.getNodeProperties( this );
  6523. const varying = this.setupVarying( builder );
  6524. if ( properties[ propertyKey ] === undefined ) {
  6525. const type = this.getNodeType( builder );
  6526. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  6527. if ( builder.shaderStage === NodeShaderStage.VERTEX ) {
  6528. const snippet = properties.node.build( builder, type );
  6529. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  6530. } else {
  6531. // force node run in vertex stage
  6532. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  6533. }
  6534. properties[ propertyKey ] = propertyName;
  6535. }
  6536. return builder.getPropertyName( varying );
  6537. }
  6538. }
  6539. /**
  6540. * TSL function for creating a varying node.
  6541. *
  6542. * @tsl
  6543. * @function
  6544. * @param {Node} node - The node for which a varying should be created.
  6545. * @param {?string} name - The name of the varying in the shader.
  6546. * @returns {VaryingNode}
  6547. */
  6548. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  6549. /**
  6550. * Computes a node in the vertex stage.
  6551. *
  6552. * @tsl
  6553. * @function
  6554. * @param {Node} node - The node which should be executed in the vertex stage.
  6555. * @returns {VaryingNode}
  6556. */
  6557. const vertexStage = ( node ) => varying( node );
  6558. addMethodChaining( 'toVarying', varying );
  6559. addMethodChaining( 'toVertexStage', vertexStage );
  6560. /**
  6561. * Converts the given color value from sRGB to linear-sRGB color space.
  6562. *
  6563. * @tsl
  6564. * @function
  6565. * @param {Node<vec3>} color - The sRGB color.
  6566. * @return {Node<vec3>} The linear-sRGB color.
  6567. */
  6568. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6569. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  6570. const b = color.mul( 0.0773993808 );
  6571. const factor = color.lessThanEqual( 0.04045 );
  6572. const rgbResult = mix( a, b, factor );
  6573. return rgbResult;
  6574. } ).setLayout( {
  6575. name: 'sRGBTransferEOTF',
  6576. type: 'vec3',
  6577. inputs: [
  6578. { name: 'color', type: 'vec3' }
  6579. ]
  6580. } );
  6581. /**
  6582. * Converts the given color value from linear-sRGB to sRGB color space.
  6583. *
  6584. * @tsl
  6585. * @function
  6586. * @param {Node<vec3>} color - The linear-sRGB color.
  6587. * @return {Node<vec3>} The sRGB color.
  6588. */
  6589. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6590. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  6591. const b = color.mul( 12.92 );
  6592. const factor = color.lessThanEqual( 0.0031308 );
  6593. const rgbResult = mix( a, b, factor );
  6594. return rgbResult;
  6595. } ).setLayout( {
  6596. name: 'sRGBTransferOETF',
  6597. type: 'vec3',
  6598. inputs: [
  6599. { name: 'color', type: 'vec3' }
  6600. ]
  6601. } );
  6602. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  6603. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  6604. /**
  6605. * This node represents a color space conversion. Meaning it converts
  6606. * a color value from a source to a target color space.
  6607. *
  6608. * @augments TempNode
  6609. */
  6610. class ColorSpaceNode extends TempNode {
  6611. static get type() {
  6612. return 'ColorSpaceNode';
  6613. }
  6614. /**
  6615. * Constructs a new color space node.
  6616. *
  6617. * @param {Node} colorNode - Represents the color to convert.
  6618. * @param {string} source - The source color space.
  6619. * @param {string} target - The target color space.
  6620. */
  6621. constructor( colorNode, source, target ) {
  6622. super( 'vec4' );
  6623. /**
  6624. * Represents the color to convert.
  6625. *
  6626. * @type {Node}
  6627. */
  6628. this.colorNode = colorNode;
  6629. /**
  6630. * The source color space.
  6631. *
  6632. * @type {string}
  6633. */
  6634. this.source = source;
  6635. /**
  6636. * The target color space.
  6637. *
  6638. * @type {string}
  6639. */
  6640. this.target = target;
  6641. }
  6642. /**
  6643. * This method resolves the constants `WORKING_COLOR_SPACE` and
  6644. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  6645. * color management and renderer.
  6646. *
  6647. * @param {NodeBuilder} builder - The current node builder.
  6648. * @param {string} colorSpace - The color space to resolve.
  6649. * @return {string} The resolved color space.
  6650. */
  6651. resolveColorSpace( builder, colorSpace ) {
  6652. if ( colorSpace === WORKING_COLOR_SPACE ) {
  6653. return ColorManagement.workingColorSpace;
  6654. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  6655. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  6656. }
  6657. return colorSpace;
  6658. }
  6659. setup( builder ) {
  6660. const { colorNode } = this;
  6661. const source = this.resolveColorSpace( builder, this.source );
  6662. const target = this.resolveColorSpace( builder, this.target );
  6663. let outputNode = colorNode;
  6664. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  6665. return outputNode;
  6666. }
  6667. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  6668. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  6669. }
  6670. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  6671. outputNode = vec4(
  6672. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  6673. outputNode.a
  6674. );
  6675. }
  6676. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  6677. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  6678. }
  6679. return outputNode;
  6680. }
  6681. }
  6682. /**
  6683. * TSL function for converting a given color node from the current working color space to the given color space.
  6684. *
  6685. * @tsl
  6686. * @function
  6687. * @param {Node} node - Represents the node to convert.
  6688. * @param {string} targetColorSpace - The target color space.
  6689. * @returns {ColorSpaceNode}
  6690. */
  6691. const workingToColorSpace = ( node, targetColorSpace ) => new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace );
  6692. /**
  6693. * TSL function for converting a given color node from the given color space to the current working color space.
  6694. *
  6695. * @tsl
  6696. * @function
  6697. * @param {Node} node - Represents the node to convert.
  6698. * @param {string} sourceColorSpace - The source color space.
  6699. * @returns {ColorSpaceNode}
  6700. */
  6701. const colorSpaceToWorking = ( node, sourceColorSpace ) => new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE );
  6702. /**
  6703. * TSL function for converting a given color node from one color space to another one.
  6704. *
  6705. * @tsl
  6706. * @function
  6707. * @param {Node} node - Represents the node to convert.
  6708. * @param {string} sourceColorSpace - The source color space.
  6709. * @param {string} targetColorSpace - The target color space.
  6710. * @returns {ColorSpaceNode}
  6711. */
  6712. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace );
  6713. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6714. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6715. // TODO: Avoid duplicated code and use only ReferenceBaseNode or ReferenceNode
  6716. /**
  6717. * This class is only relevant if the referenced property is array-like.
  6718. * In this case, `ReferenceElementNode` allows to refer to a specific
  6719. * element inside the data structure via an index.
  6720. *
  6721. * @augments ArrayElementNode
  6722. */
  6723. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6724. static get type() {
  6725. return 'ReferenceElementNode';
  6726. }
  6727. /**
  6728. * Constructs a new reference element node.
  6729. *
  6730. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6731. * @param {Node} indexNode - The index node that defines the element access.
  6732. */
  6733. constructor( referenceNode, indexNode ) {
  6734. super( referenceNode, indexNode );
  6735. /**
  6736. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6737. * property references to the current node.
  6738. *
  6739. * @type {?ReferenceBaseNode}
  6740. * @default null
  6741. */
  6742. this.referenceNode = referenceNode;
  6743. /**
  6744. * This flag can be used for type testing.
  6745. *
  6746. * @type {boolean}
  6747. * @readonly
  6748. * @default true
  6749. */
  6750. this.isReferenceElementNode = true;
  6751. }
  6752. /**
  6753. * This method is overwritten since the node type is inferred from
  6754. * the uniform type of the reference node.
  6755. *
  6756. * @return {string} The node type.
  6757. */
  6758. generateNodeType() {
  6759. return this.referenceNode.uniformType;
  6760. }
  6761. generate( builder ) {
  6762. const snippet = super.generate( builder );
  6763. const arrayType = this.referenceNode.getNodeType();
  6764. const elementType = this.getNodeType();
  6765. return builder.format( snippet, arrayType, elementType );
  6766. }
  6767. };
  6768. /**
  6769. * Base class for nodes which establishes a reference to a property of another object.
  6770. * In this way, the value of the node is automatically linked to the value of
  6771. * referenced object. Reference nodes internally represent the linked value
  6772. * as a uniform.
  6773. *
  6774. * @augments Node
  6775. */
  6776. class ReferenceBaseNode extends Node {
  6777. static get type() {
  6778. return 'ReferenceBaseNode';
  6779. }
  6780. /**
  6781. * Constructs a new reference base node.
  6782. *
  6783. * @param {string} property - The name of the property the node refers to.
  6784. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6785. * @param {?Object} [object=null] - The object the property belongs to.
  6786. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6787. */
  6788. constructor( property, uniformType, object = null, count = null ) {
  6789. super();
  6790. /**
  6791. * The name of the property the node refers to.
  6792. *
  6793. * @type {string}
  6794. */
  6795. this.property = property;
  6796. /**
  6797. * The uniform type that should be used to represent the property value.
  6798. *
  6799. * @type {string}
  6800. */
  6801. this.uniformType = uniformType;
  6802. /**
  6803. * The object the property belongs to.
  6804. *
  6805. * @type {?Object}
  6806. * @default null
  6807. */
  6808. this.object = object;
  6809. /**
  6810. * When the linked property is an array, this parameter defines its length.
  6811. *
  6812. * @type {?number}
  6813. * @default null
  6814. */
  6815. this.count = count;
  6816. /**
  6817. * The property name might have dots so nested properties can be referred.
  6818. * The hierarchy of the names is stored inside this array.
  6819. *
  6820. * @type {Array<string>}
  6821. */
  6822. this.properties = property.split( '.' );
  6823. /**
  6824. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6825. * since the final reference might be updated from calling code.
  6826. *
  6827. * @type {?Object}
  6828. * @default null
  6829. */
  6830. this.reference = object;
  6831. /**
  6832. * The uniform node that holds the value of the reference node.
  6833. *
  6834. * @type {UniformNode}
  6835. * @default null
  6836. */
  6837. this.node = null;
  6838. /**
  6839. * The uniform group of the internal uniform.
  6840. *
  6841. * @type {UniformGroupNode}
  6842. * @default null
  6843. */
  6844. this.group = null;
  6845. /**
  6846. * Overwritten since reference nodes are updated per object.
  6847. *
  6848. * @type {string}
  6849. * @default 'object'
  6850. */
  6851. this.updateType = NodeUpdateType.OBJECT;
  6852. }
  6853. /**
  6854. * Sets the uniform group for this reference node.
  6855. *
  6856. * @param {UniformGroupNode} group - The uniform group to set.
  6857. * @return {ReferenceBaseNode} A reference to this node.
  6858. */
  6859. setGroup( group ) {
  6860. this.group = group;
  6861. return this;
  6862. }
  6863. /**
  6864. * When the referred property is array-like, this method can be used
  6865. * to access elements via an index node.
  6866. *
  6867. * @param {IndexNode} indexNode - indexNode.
  6868. * @return {ReferenceElementNode} A reference to an element.
  6869. */
  6870. element( indexNode ) {
  6871. return new ReferenceElementNode$1( this, nodeObject( indexNode ) );
  6872. }
  6873. /**
  6874. * Sets the node type which automatically defines the internal
  6875. * uniform type.
  6876. *
  6877. * @param {string} uniformType - The type to set.
  6878. */
  6879. setNodeType( uniformType ) {
  6880. const node = uniform( null, uniformType );
  6881. if ( this.group !== null ) {
  6882. node.setGroup( this.group );
  6883. }
  6884. this.node = node;
  6885. }
  6886. /**
  6887. * This method is overwritten since the node type is inferred from
  6888. * the type of the reference node.
  6889. *
  6890. * @param {NodeBuilder} builder - The current node builder.
  6891. * @return {string} The node type.
  6892. */
  6893. generateNodeType( builder ) {
  6894. if ( this.node === null ) {
  6895. this.updateReference( builder );
  6896. this.updateValue();
  6897. }
  6898. return this.node.getNodeType( builder );
  6899. }
  6900. /**
  6901. * Returns the property value from the given referred object.
  6902. *
  6903. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6904. * @return {any} The value.
  6905. */
  6906. getValueFromReference( object = this.reference ) {
  6907. const { properties } = this;
  6908. let value = object[ properties[ 0 ] ];
  6909. for ( let i = 1; i < properties.length; i ++ ) {
  6910. value = value[ properties[ i ] ];
  6911. }
  6912. return value;
  6913. }
  6914. /**
  6915. * Allows to update the reference based on the given state. The state is only
  6916. * evaluated {@link ReferenceBaseNode#object} is not set.
  6917. *
  6918. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6919. * @return {Object} The updated reference.
  6920. */
  6921. updateReference( state ) {
  6922. this.reference = this.object !== null ? this.object : state.object;
  6923. return this.reference;
  6924. }
  6925. /**
  6926. * The output of the reference node is the internal uniform node.
  6927. *
  6928. * @return {UniformNode} The output node.
  6929. */
  6930. setup() {
  6931. this.updateValue();
  6932. return this.node;
  6933. }
  6934. /**
  6935. * Overwritten to update the internal uniform value.
  6936. *
  6937. * @param {NodeFrame} frame - A reference to the current node frame.
  6938. */
  6939. update( /*frame*/ ) {
  6940. this.updateValue();
  6941. }
  6942. /**
  6943. * Retrieves the value from the referred object property and uses it
  6944. * to updated the internal uniform.
  6945. */
  6946. updateValue() {
  6947. if ( this.node === null ) this.setNodeType( this.uniformType );
  6948. const value = this.getValueFromReference();
  6949. if ( Array.isArray( value ) ) {
  6950. this.node.array = value;
  6951. } else {
  6952. this.node.value = value;
  6953. }
  6954. }
  6955. }
  6956. /**
  6957. * TSL function for creating a reference base node.
  6958. *
  6959. * @tsl
  6960. * @function
  6961. * @param {string} name - The name of the property the node refers to.
  6962. * @param {string} type - The uniform type that should be used to represent the property value.
  6963. * @param {Object} object - The object the property belongs to.
  6964. * @returns {ReferenceBaseNode}
  6965. */
  6966. const reference$1 = ( name, type, object ) => new ReferenceBaseNode( name, type, object );
  6967. /**
  6968. * This node is a special type of reference node which is intended
  6969. * for linking renderer properties with node values.
  6970. * ```js
  6971. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6972. * ```
  6973. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6974. * automatically be updated.
  6975. *
  6976. * @augments ReferenceBaseNode
  6977. */
  6978. class RendererReferenceNode extends ReferenceBaseNode {
  6979. static get type() {
  6980. return 'RendererReferenceNode';
  6981. }
  6982. /**
  6983. * Constructs a new renderer reference node.
  6984. *
  6985. * @param {string} property - The name of the property the node refers to.
  6986. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6987. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6988. * the node refers to the renderer of the current state.
  6989. */
  6990. constructor( property, inputType, renderer = null ) {
  6991. super( property, inputType, renderer );
  6992. /**
  6993. * The renderer the property belongs to. When no renderer is set,
  6994. * the node refers to the renderer of the current state.
  6995. *
  6996. * @type {?Renderer}
  6997. * @default null
  6998. */
  6999. this.renderer = renderer;
  7000. this.setGroup( renderGroup );
  7001. }
  7002. /**
  7003. * Updates the reference based on the given state. The state is only evaluated
  7004. * {@link RendererReferenceNode#renderer} is not set.
  7005. *
  7006. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  7007. * @return {Object} The updated reference.
  7008. */
  7009. updateReference( state ) {
  7010. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  7011. return this.reference;
  7012. }
  7013. }
  7014. /**
  7015. * TSL function for creating a renderer reference node.
  7016. *
  7017. * @tsl
  7018. * @function
  7019. * @param {string} name - The name of the property the node refers to.
  7020. * @param {string} type - The uniform type that should be used to represent the property value.
  7021. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  7022. * the node refers to the renderer of the current state.
  7023. * @returns {RendererReferenceNode}
  7024. */
  7025. const rendererReference = ( name, type, renderer = null ) => new RendererReferenceNode( name, type, renderer );
  7026. /**
  7027. * This node represents a tone mapping operation.
  7028. *
  7029. * @augments TempNode
  7030. */
  7031. class ToneMappingNode extends TempNode {
  7032. static get type() {
  7033. return 'ToneMappingNode';
  7034. }
  7035. /**
  7036. * Constructs a new tone mapping node.
  7037. *
  7038. * @param {number} toneMapping - The tone mapping type.
  7039. * @param {Node} exposureNode - The tone mapping exposure.
  7040. * @param {Node} [colorNode=null] - The color node to process.
  7041. */
  7042. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  7043. super( 'vec3' );
  7044. /**
  7045. * The tone mapping type.
  7046. *
  7047. * @private
  7048. * @type {number}
  7049. */
  7050. this._toneMapping = toneMapping;
  7051. /**
  7052. * The tone mapping exposure.
  7053. *
  7054. * @type {Node}
  7055. * @default null
  7056. */
  7057. this.exposureNode = exposureNode;
  7058. /**
  7059. * Represents the color to process.
  7060. *
  7061. * @type {?Node}
  7062. * @default null
  7063. */
  7064. this.colorNode = colorNode;
  7065. }
  7066. /**
  7067. * Overwrites the default `customCacheKey()` implementation by including the tone
  7068. * mapping type into the cache key.
  7069. *
  7070. * @return {number} The hash.
  7071. */
  7072. customCacheKey() {
  7073. return hash$1( this._toneMapping );
  7074. }
  7075. /**
  7076. * Sets the tone mapping type.
  7077. *
  7078. * @param {number} value - The tone mapping type.
  7079. * @return {ToneMappingNode} A reference to this node.
  7080. */
  7081. setToneMapping( value ) {
  7082. this._toneMapping = value;
  7083. return this;
  7084. }
  7085. /**
  7086. * Gets the tone mapping type.
  7087. *
  7088. * @returns {number} The tone mapping type.
  7089. */
  7090. getToneMapping() {
  7091. return this._toneMapping;
  7092. }
  7093. setup( builder ) {
  7094. const colorNode = this.colorNode || builder.context.color;
  7095. const toneMapping = this._toneMapping;
  7096. if ( toneMapping === NoToneMapping ) return colorNode;
  7097. let outputNode = null;
  7098. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  7099. if ( toneMappingFn !== null ) {
  7100. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  7101. } else {
  7102. error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  7103. outputNode = colorNode;
  7104. }
  7105. return outputNode;
  7106. }
  7107. }
  7108. /**
  7109. * TSL function for creating a tone mapping node.
  7110. *
  7111. * @tsl
  7112. * @function
  7113. * @param {number} mapping - The tone mapping type.
  7114. * @param {Node<float> | number} exposure - The tone mapping exposure.
  7115. * @param {Node<vec3> | Color} color - The color node to process.
  7116. * @returns {ToneMappingNode<vec3>}
  7117. */
  7118. const toneMapping = ( mapping, exposure, color ) => new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) );
  7119. /**
  7120. * TSL object that represents the global tone mapping exposure of the renderer.
  7121. *
  7122. * @tsl
  7123. * @type {RendererReferenceNode<vec3>}
  7124. */
  7125. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  7126. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  7127. /**
  7128. * Internal buffer attribute library.
  7129. *
  7130. * @private
  7131. * @type {WeakMap<TypedArray, InterleavedBuffer>}
  7132. */
  7133. const _bufferLib = new WeakMap();
  7134. /**
  7135. * Internal method for retrieving or creating interleaved buffers.
  7136. *
  7137. * @private
  7138. * @param {TypedArray} value - The attribute data.
  7139. * @param {number} itemSize - The attribute item size.
  7140. * @returns {InterleavedBuffer} The interleaved buffer.
  7141. */
  7142. function _getBufferAttribute( value, itemSize ) {
  7143. let buffer = _bufferLib.get( value );
  7144. if ( buffer === undefined ) {
  7145. buffer = new InterleavedBuffer( value, itemSize );
  7146. _bufferLib.set( value, buffer );
  7147. }
  7148. return buffer;
  7149. }
  7150. /**
  7151. * In earlier `three.js` versions it was only possible to define attribute data
  7152. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  7153. * on the node level.
  7154. * ```js
  7155. * const geometry = new THREE.PlaneGeometry();
  7156. * const positionAttribute = geometry.getAttribute( 'position' );
  7157. *
  7158. * const colors = [];
  7159. * for ( let i = 0; i < position.count; i ++ ) {
  7160. * colors.push( 1, 0, 0 );
  7161. * }
  7162. *
  7163. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  7164. * ```
  7165. * This new approach is especially interesting when geometry data are generated via
  7166. * compute shaders. The below line converts a storage buffer into an attribute node.
  7167. * ```js
  7168. * material.positionNode = positionBuffer.toAttribute();
  7169. * ```
  7170. * @augments InputNode
  7171. */
  7172. class BufferAttributeNode extends InputNode {
  7173. static get type() {
  7174. return 'BufferAttributeNode';
  7175. }
  7176. /**
  7177. * Constructs a new buffer attribute node.
  7178. *
  7179. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  7180. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  7181. * @param {number} [bufferStride=0] - The buffer stride.
  7182. * @param {number} [bufferOffset=0] - The buffer offset.
  7183. */
  7184. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  7185. super( value, bufferType );
  7186. /**
  7187. * This flag can be used for type testing.
  7188. *
  7189. * @type {boolean}
  7190. * @readonly
  7191. * @default true
  7192. */
  7193. this.isBufferNode = true;
  7194. /**
  7195. * The buffer type (e.g. `'vec3'`).
  7196. *
  7197. * @type {?string}
  7198. * @default null
  7199. */
  7200. this.bufferType = bufferType;
  7201. /**
  7202. * The buffer stride.
  7203. *
  7204. * @type {number}
  7205. * @default 0
  7206. */
  7207. this.bufferStride = bufferStride;
  7208. /**
  7209. * The buffer offset.
  7210. *
  7211. * @type {number}
  7212. * @default 0
  7213. */
  7214. this.bufferOffset = bufferOffset;
  7215. /**
  7216. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  7217. * if you are planning to update the attribute data per frame.
  7218. *
  7219. * @type {number}
  7220. * @default StaticDrawUsage
  7221. */
  7222. this.usage = StaticDrawUsage;
  7223. /**
  7224. * Whether the attribute is instanced or not.
  7225. *
  7226. * @type {boolean}
  7227. * @default false
  7228. */
  7229. this.instanced = false;
  7230. /**
  7231. * A reference to the buffer attribute.
  7232. *
  7233. * @type {?BufferAttribute}
  7234. * @default null
  7235. */
  7236. this.attribute = null;
  7237. /**
  7238. * `BufferAttributeNode` sets this property to `true` by default.
  7239. *
  7240. * @type {boolean}
  7241. * @default true
  7242. */
  7243. this.global = true;
  7244. if ( value && value.isBufferAttribute === true && value.itemSize <= 4 ) {
  7245. this.attribute = value;
  7246. this.usage = value.usage;
  7247. this.instanced = value.isInstancedBufferAttribute;
  7248. }
  7249. }
  7250. /**
  7251. * This method is overwritten since the attribute data might be shared
  7252. * and thus the hash should be shared as well.
  7253. *
  7254. * @param {NodeBuilder} builder - The current node builder.
  7255. * @return {string} The hash.
  7256. */
  7257. getHash( builder ) {
  7258. let id;
  7259. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  7260. let bufferData = builder.globalCache.getData( this.value );
  7261. if ( bufferData === undefined ) {
  7262. bufferData = {
  7263. node: this
  7264. };
  7265. builder.globalCache.setData( this.value, bufferData );
  7266. }
  7267. id = bufferData.node.id;
  7268. } else {
  7269. id = this.id;
  7270. }
  7271. return String( id );
  7272. }
  7273. /**
  7274. * This method is overwritten since the node type is inferred from
  7275. * the buffer attribute.
  7276. *
  7277. * @param {NodeBuilder} builder - The current node builder.
  7278. * @return {string} The node type.
  7279. */
  7280. generateNodeType( builder ) {
  7281. if ( this.bufferType === null ) {
  7282. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  7283. }
  7284. return this.bufferType;
  7285. }
  7286. /**
  7287. * Depending on which value was passed to the node, `setup()` behaves
  7288. * differently. If no instance of `BufferAttribute` was passed, the method
  7289. * creates an internal attribute and configures it respectively.
  7290. *
  7291. * @param {NodeBuilder} builder - The current node builder.
  7292. */
  7293. setup( builder ) {
  7294. if ( this.attribute !== null ) return;
  7295. //
  7296. const type = this.getNodeType( builder );
  7297. const itemSize = builder.getTypeLength( type );
  7298. const value = this.value;
  7299. const stride = this.bufferStride || itemSize;
  7300. const offset = this.bufferOffset;
  7301. let buffer;
  7302. if ( value.isInterleavedBuffer === true ) {
  7303. buffer = value;
  7304. } else if ( value.isBufferAttribute === true ) {
  7305. buffer = _getBufferAttribute( value.array, stride );
  7306. } else {
  7307. buffer = _getBufferAttribute( value, stride );
  7308. }
  7309. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  7310. buffer.setUsage( this.usage );
  7311. this.attribute = bufferAttribute;
  7312. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  7313. }
  7314. /**
  7315. * Generates the code snippet of the buffer attribute node.
  7316. *
  7317. * @param {NodeBuilder} builder - The current node builder.
  7318. * @return {string} The generated code snippet.
  7319. */
  7320. generate( builder ) {
  7321. const nodeType = this.getNodeType( builder );
  7322. const nodeName = builder.context.nodeName;
  7323. if ( nodeName !== undefined ) delete builder.context.nodeName; // deleting when consumed
  7324. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType, nodeName );
  7325. const propertyName = builder.getPropertyName( nodeAttribute );
  7326. let output = null;
  7327. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  7328. this.name = propertyName;
  7329. output = propertyName;
  7330. } else {
  7331. let varyingName;
  7332. if ( nodeName ) {
  7333. varyingName = nodeName + 'Varying';
  7334. }
  7335. const nodeVarying = varying( this, varyingName );
  7336. output = nodeVarying.build( builder, nodeType );
  7337. }
  7338. return output;
  7339. }
  7340. /**
  7341. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  7342. *
  7343. * @param {NodeBuilder} builder - The current node builder.
  7344. * @return {string} The input type.
  7345. */
  7346. getInputType( /*builder*/ ) {
  7347. return 'bufferAttribute';
  7348. }
  7349. /**
  7350. * Sets the `usage` property to the given value.
  7351. *
  7352. * @param {number} value - The usage to set.
  7353. * @return {BufferAttributeNode} A reference to this node.
  7354. */
  7355. setUsage( value ) {
  7356. this.usage = value;
  7357. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  7358. this.attribute.usage = value;
  7359. }
  7360. return this;
  7361. }
  7362. /**
  7363. * Sets the `instanced` property to the given value.
  7364. *
  7365. * @param {boolean} value - The value to set.
  7366. * @return {BufferAttributeNode} A reference to this node.
  7367. */
  7368. setInstanced( value ) {
  7369. this.instanced = value;
  7370. return this;
  7371. }
  7372. }
  7373. /**
  7374. * Internal method for creating buffer attribute nodes.
  7375. *
  7376. * @private
  7377. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7378. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7379. * @param {number} [stride=0] - The buffer stride.
  7380. * @param {number} [offset=0] - The buffer offset.
  7381. * @param {number} [usage=StaticDrawUsage] - The buffer usage.
  7382. * @param {boolean} [instanced=false] - Whether the buffer is instanced.
  7383. * @returns {BufferAttributeNode|Node} The buffer attribute node.
  7384. */
  7385. function createBufferAttribute( array, type = null, stride = 0, offset = 0, usage = StaticDrawUsage, instanced = false ) {
  7386. if ( type === 'mat3' || ( type === null && array.itemSize === 9 ) ) {
  7387. return mat3(
  7388. new BufferAttributeNode( array, 'vec3', 9, 0 ).setUsage( usage ).setInstanced( instanced ),
  7389. new BufferAttributeNode( array, 'vec3', 9, 3 ).setUsage( usage ).setInstanced( instanced ),
  7390. new BufferAttributeNode( array, 'vec3', 9, 6 ).setUsage( usage ).setInstanced( instanced )
  7391. );
  7392. } else if ( type === 'mat4' || ( type === null && array.itemSize === 16 ) ) {
  7393. return mat4(
  7394. new BufferAttributeNode( array, 'vec4', 16, 0 ).setUsage( usage ).setInstanced( instanced ),
  7395. new BufferAttributeNode( array, 'vec4', 16, 4 ).setUsage( usage ).setInstanced( instanced ),
  7396. new BufferAttributeNode( array, 'vec4', 16, 8 ).setUsage( usage ).setInstanced( instanced ),
  7397. new BufferAttributeNode( array, 'vec4', 16, 12 ).setUsage( usage ).setInstanced( instanced )
  7398. );
  7399. }
  7400. return new BufferAttributeNode( array, type, stride, offset ).setUsage( usage );
  7401. }
  7402. /**
  7403. * TSL function for creating a buffer attribute node.
  7404. *
  7405. * @tsl
  7406. * @function
  7407. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7408. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7409. * @param {number} [stride=0] - The buffer stride.
  7410. * @param {number} [offset=0] - The buffer offset.
  7411. * @returns {BufferAttributeNode|Node}
  7412. */
  7413. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset );
  7414. /**
  7415. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  7416. * Use this function if attribute data are updated per frame.
  7417. *
  7418. * @tsl
  7419. * @function
  7420. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7421. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7422. * @param {number} [stride=0] - The buffer stride.
  7423. * @param {number} [offset=0] - The buffer offset.
  7424. * @returns {BufferAttributeNode|Node}
  7425. */
  7426. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage );
  7427. /**
  7428. * TSL function for creating a buffer attribute node but with enabled instancing
  7429. *
  7430. * @tsl
  7431. * @function
  7432. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7433. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7434. * @param {number} [stride=0] - The buffer stride.
  7435. * @param {number} [offset=0] - The buffer offset.
  7436. * @returns {BufferAttributeNode|Node}
  7437. */
  7438. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, StaticDrawUsage, true );
  7439. /**
  7440. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  7441. *
  7442. * @tsl
  7443. * @function
  7444. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7445. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7446. * @param {number} [stride=0] - The buffer stride.
  7447. * @param {number} [offset=0] - The buffer offset.
  7448. * @returns {BufferAttributeNode|Node}
  7449. */
  7450. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage, true );
  7451. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  7452. /**
  7453. * This class represents shader indices of different types. The following predefined node
  7454. * objects cover frequent use cases:
  7455. *
  7456. * - `vertexIndex`: The index of a vertex within a mesh.
  7457. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  7458. * - `drawIndex`: The index of a draw call.
  7459. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  7460. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  7461. * - `subgroupIndex`: The index of a compute invocation's subgroup within its workgroup.
  7462. *
  7463. * @augments Node
  7464. */
  7465. class IndexNode extends Node {
  7466. static get type() {
  7467. return 'IndexNode';
  7468. }
  7469. /**
  7470. * Constructs a new index node.
  7471. *
  7472. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationGlobal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  7473. */
  7474. constructor( scope ) {
  7475. super( 'uint' );
  7476. /**
  7477. * The scope of the index node.
  7478. *
  7479. * @type {string}
  7480. */
  7481. this.scope = scope;
  7482. /**
  7483. * This flag can be used for type testing.
  7484. *
  7485. * @type {boolean}
  7486. * @readonly
  7487. * @default true
  7488. */
  7489. this.isIndexNode = true;
  7490. }
  7491. generate( builder ) {
  7492. const nodeType = this.getNodeType( builder );
  7493. const scope = this.scope;
  7494. let propertyName;
  7495. if ( scope === IndexNode.VERTEX ) {
  7496. propertyName = builder.getVertexIndex();
  7497. } else if ( scope === IndexNode.INSTANCE ) {
  7498. propertyName = builder.getInstanceIndex();
  7499. } else if ( scope === IndexNode.DRAW ) {
  7500. propertyName = builder.getDrawIndex();
  7501. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  7502. propertyName = builder.getInvocationLocalIndex();
  7503. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  7504. propertyName = builder.getInvocationSubgroupIndex();
  7505. } else if ( scope === IndexNode.SUBGROUP ) {
  7506. propertyName = builder.getSubgroupIndex();
  7507. } else {
  7508. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  7509. }
  7510. let output;
  7511. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  7512. output = propertyName;
  7513. } else {
  7514. const nodeVarying = varying( this );
  7515. output = nodeVarying.build( builder, nodeType );
  7516. }
  7517. return output;
  7518. }
  7519. }
  7520. IndexNode.VERTEX = 'vertex';
  7521. IndexNode.INSTANCE = 'instance';
  7522. IndexNode.SUBGROUP = 'subgroup';
  7523. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  7524. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  7525. IndexNode.DRAW = 'draw';
  7526. /**
  7527. * TSL object that represents the index of a vertex within a mesh.
  7528. *
  7529. * @tsl
  7530. * @type {IndexNode}
  7531. */
  7532. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  7533. /**
  7534. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  7535. *
  7536. * @tsl
  7537. * @type {IndexNode}
  7538. */
  7539. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  7540. /**
  7541. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  7542. *
  7543. * @tsl
  7544. * @type {IndexNode}
  7545. */
  7546. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  7547. /**
  7548. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  7549. *
  7550. * @tsl
  7551. * @type {IndexNode}
  7552. */
  7553. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  7554. /**
  7555. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  7556. *
  7557. * @tsl
  7558. * @type {IndexNode}
  7559. */
  7560. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  7561. /**
  7562. * TSL object that represents the index of a draw call.
  7563. *
  7564. * @tsl
  7565. * @type {IndexNode}
  7566. */
  7567. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  7568. /**
  7569. * Represents a compute shader node.
  7570. *
  7571. * @augments Node
  7572. */
  7573. class ComputeNode extends Node {
  7574. static get type() {
  7575. return 'ComputeNode';
  7576. }
  7577. /**
  7578. * Constructs a new compute node.
  7579. *
  7580. * @param {Node} computeNode - The node that defines the compute shader logic.
  7581. * @param {Array<number>} workgroupSize - An array defining the X, Y, and Z dimensions of the workgroup for compute shader execution.
  7582. */
  7583. constructor( computeNode, workgroupSize ) {
  7584. super( 'void' );
  7585. /**
  7586. * This flag can be used for type testing.
  7587. *
  7588. * @type {boolean}
  7589. * @readonly
  7590. * @default true
  7591. */
  7592. this.isComputeNode = true;
  7593. /**
  7594. * The node that defines the compute shader logic.
  7595. *
  7596. * @type {Node}
  7597. */
  7598. this.computeNode = computeNode;
  7599. /**
  7600. * An array defining the X, Y, and Z dimensions of the workgroup for compute shader execution.
  7601. *
  7602. * @type {Array<number>}
  7603. * @default [ 64 ]
  7604. */
  7605. this.workgroupSize = workgroupSize;
  7606. /**
  7607. * The total number of threads (invocations) to execute. If it is a number, it will be used
  7608. * to automatically generate bounds checking against `instanceIndex`.
  7609. *
  7610. * @type {number|Array<number>}
  7611. */
  7612. this.count = null;
  7613. /**
  7614. * The dispatch size for workgroups on X, Y, and Z axes.
  7615. * Used directly if `count` is not provided.
  7616. *
  7617. * @type {number|Array<number>}
  7618. */
  7619. this.dispatchSize = null;
  7620. /**
  7621. * The version of the node.
  7622. *
  7623. * @type {number}
  7624. */
  7625. this.version = 1;
  7626. /**
  7627. * The name or label of the uniform.
  7628. *
  7629. * @type {string}
  7630. * @default ''
  7631. */
  7632. this.name = '';
  7633. /**
  7634. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  7635. * is executed once per object by default.
  7636. *
  7637. * @type {string}
  7638. * @default 'object'
  7639. */
  7640. this.updateBeforeType = NodeUpdateType.OBJECT;
  7641. /**
  7642. * A callback executed when the compute node finishes initialization.
  7643. *
  7644. * @type {?Function}
  7645. */
  7646. this.onInitFunction = null;
  7647. /**
  7648. * A uniform node holding the dispatch count for bounds checking.
  7649. * Created automatically when `count` is a number.
  7650. *
  7651. * @type {?UniformNode}
  7652. */
  7653. this.countNode = null;
  7654. }
  7655. /**
  7656. * Executes the `dispose` event for this node.
  7657. */
  7658. dispose() {
  7659. this.dispatchEvent( { type: 'dispose' } );
  7660. }
  7661. /**
  7662. * Sets the {@link ComputeNode#name} property.
  7663. *
  7664. * @param {string} name - The name of the uniform.
  7665. * @return {ComputeNode} A reference to this node.
  7666. */
  7667. setName( name ) {
  7668. this.name = name;
  7669. return this;
  7670. }
  7671. /**
  7672. * Sets the {@link ComputeNode#name} property.
  7673. *
  7674. * @deprecated
  7675. * @param {string} name - The name of the uniform.
  7676. * @return {ComputeNode} A reference to this node.
  7677. */
  7678. label( name ) {
  7679. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.', new StackTrace() ); // @deprecated r179
  7680. return this.setName( name );
  7681. }
  7682. /**
  7683. * Sets the callback to run during initialization.
  7684. *
  7685. * @param {Function} callback - The callback function.
  7686. * @return {ComputeNode} A reference to this node.
  7687. */
  7688. onInit( callback ) {
  7689. this.onInitFunction = callback;
  7690. return this;
  7691. }
  7692. /**
  7693. * The method execute the compute for this node.
  7694. *
  7695. * @param {NodeFrame} frame - A reference to the current node frame.
  7696. */
  7697. updateBefore( { renderer } ) {
  7698. renderer.compute( this );
  7699. }
  7700. setup( builder ) {
  7701. if ( this.count !== null && this.countNode === null ) {
  7702. this.countNode = uniform( this.count, 'uint' ).onObjectUpdate( () => this.count );
  7703. }
  7704. const result = this.computeNode.build( builder );
  7705. if ( result ) {
  7706. const properties = builder.getNodeProperties( this );
  7707. properties.outputComputeNode = result.outputNode;
  7708. result.outputNode = null;
  7709. }
  7710. return result;
  7711. }
  7712. generate( builder, output ) {
  7713. const { shaderStage } = builder;
  7714. if ( shaderStage === 'compute' ) {
  7715. const snippet = this.computeNode.build( builder, 'void' );
  7716. if ( snippet !== '' ) {
  7717. builder.addLineFlowCode( snippet, this );
  7718. }
  7719. if ( this.count !== null && builder.allowEarlyReturns === true ) {
  7720. const countSnippet = this.countNode.build( builder, 'uint' );
  7721. const indexSnippet = instanceIndex.build( builder, 'uint' );
  7722. builder.flow.code = `${ builder.tab }if ( ${ indexSnippet } >= ${ countSnippet } ) { return; }\n\n${ builder.flow.code }`;
  7723. }
  7724. } else {
  7725. const properties = builder.getNodeProperties( this );
  7726. const outputComputeNode = properties.outputComputeNode;
  7727. if ( outputComputeNode ) {
  7728. return outputComputeNode.build( builder, output );
  7729. }
  7730. }
  7731. }
  7732. }
  7733. /**
  7734. * TSL function for creating a compute kernel node.
  7735. *
  7736. * @tsl
  7737. * @function
  7738. * @param {Node} node - The TSL logic for the compute shader.
  7739. * @param {Array<number>} [workgroupSize=[64]] - The workgroup size.
  7740. * @returns {ComputeNode}
  7741. */
  7742. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  7743. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  7744. error( 'TSL: compute() workgroupSize must have 1, 2, or 3 elements', new StackTrace() );
  7745. }
  7746. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  7747. const val = workgroupSize[ i ];
  7748. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  7749. error( `TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer`, new StackTrace() );
  7750. }
  7751. }
  7752. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  7753. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  7754. //
  7755. return new ComputeNode( nodeObject( node ), workgroupSize );
  7756. };
  7757. /**
  7758. * TSL function for creating a compute node.
  7759. *
  7760. * @tsl
  7761. * @function
  7762. * @param {Node} node - The TSL logic for the compute shader.
  7763. * @param {number|Array<number>} count - The compute count or dispatch size.
  7764. * @param {Array<number>} [workgroupSize=[64]] - The workgroup size.
  7765. * @returns {ComputeNode}
  7766. , */
  7767. const compute = ( node, count, workgroupSize ) => {
  7768. const computeNode = computeKernel( node, workgroupSize );
  7769. if ( typeof count === 'number' ) {
  7770. computeNode.count = count;
  7771. } else {
  7772. computeNode.dispatchSize = count;
  7773. }
  7774. return computeNode;
  7775. };
  7776. addMethodChaining( 'compute', compute );
  7777. addMethodChaining( 'computeKernel', computeKernel );
  7778. /**
  7779. * This node can be used as a cache management component for another node.
  7780. * Caching is in general used by default in {@link NodeBuilder} but this node
  7781. * allows the usage of a shared parent cache during the build process.
  7782. *
  7783. * @augments Node
  7784. */
  7785. class IsolateNode extends Node {
  7786. static get type() {
  7787. return 'IsolateNode';
  7788. }
  7789. /**
  7790. * Constructs a new cache node.
  7791. *
  7792. * @param {Node} node - The node that should be cached.
  7793. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7794. */
  7795. constructor( node, parent = true ) {
  7796. super();
  7797. /**
  7798. * The node that should be cached.
  7799. *
  7800. * @type {Node}
  7801. */
  7802. this.node = node;
  7803. /**
  7804. * Whether this node refers to a shared parent cache or not.
  7805. *
  7806. * @type {boolean}
  7807. * @default true
  7808. */
  7809. this.parent = parent;
  7810. /**
  7811. * This flag can be used for type testing.
  7812. *
  7813. * @type {boolean}
  7814. * @readonly
  7815. * @default true
  7816. */
  7817. this.isIsolateNode = true;
  7818. }
  7819. generateNodeType( builder ) {
  7820. const previousCache = builder.getCache();
  7821. const cache = builder.getCacheFromNode( this, this.parent );
  7822. builder.setCache( cache );
  7823. const nodeType = this.node.getNodeType( builder );
  7824. builder.setCache( previousCache );
  7825. return nodeType;
  7826. }
  7827. build( builder, ...params ) {
  7828. const previousCache = builder.getCache();
  7829. const cache = builder.getCacheFromNode( this, this.parent );
  7830. builder.setCache( cache );
  7831. const data = this.node.build( builder, ...params );
  7832. builder.setCache( previousCache );
  7833. return data;
  7834. }
  7835. setParent( parent ) {
  7836. this.parent = parent;
  7837. return this;
  7838. }
  7839. getParent() {
  7840. return this.parent;
  7841. }
  7842. }
  7843. /**
  7844. * TSL function for creating a cache node.
  7845. *
  7846. * @tsl
  7847. * @function
  7848. * @param {Node} node - The node that should be cached.
  7849. * @returns {IsolateNode}
  7850. */
  7851. const isolate = ( node ) => new IsolateNode( nodeObject( node ) );
  7852. /**
  7853. * TSL function for creating a cache node.
  7854. *
  7855. * @tsl
  7856. * @function
  7857. * @deprecated
  7858. * @param {Node} node - The node that should be cached.
  7859. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7860. * @returns {IsolateNode}
  7861. */
  7862. function cache( node, parent = true ) {
  7863. warn( 'TSL: "cache()" has been deprecated. Use "isolate()" instead.' ); // @deprecated r181
  7864. return isolate( node ).setParent( parent );
  7865. }
  7866. addMethodChaining( 'cache', cache );
  7867. addMethodChaining( 'isolate', isolate );
  7868. /**
  7869. * The class generates the code of a given node but returns another node in the output.
  7870. * This can be used to call a method or node that does not return a value, i.e.
  7871. * type `void` on an input where returning a value is required. Example:
  7872. *
  7873. * ```js
  7874. * material.colorNode = myColor.bypass( runVoidFn() )
  7875. *```
  7876. *
  7877. * @augments Node
  7878. */
  7879. class BypassNode extends Node {
  7880. static get type() {
  7881. return 'BypassNode';
  7882. }
  7883. /**
  7884. * Constructs a new bypass node.
  7885. *
  7886. * @param {Node} outputNode - The output node.
  7887. * @param {Node} callNode - The call node.
  7888. */
  7889. constructor( outputNode, callNode ) {
  7890. super();
  7891. /**
  7892. * This flag can be used for type testing.
  7893. *
  7894. * @type {boolean}
  7895. * @readonly
  7896. * @default true
  7897. */
  7898. this.isBypassNode = true;
  7899. /**
  7900. * The output node.
  7901. *
  7902. * @type {Node}
  7903. */
  7904. this.outputNode = outputNode;
  7905. /**
  7906. * The call node.
  7907. *
  7908. * @type {Node}
  7909. */
  7910. this.callNode = callNode;
  7911. }
  7912. generateNodeType( builder ) {
  7913. return this.outputNode.getNodeType( builder );
  7914. }
  7915. generate( builder ) {
  7916. const snippet = this.callNode.build( builder, 'void' );
  7917. if ( snippet !== '' ) {
  7918. builder.addLineFlowCode( snippet, this );
  7919. }
  7920. return this.outputNode.build( builder );
  7921. }
  7922. }
  7923. /**
  7924. * TSL function for creating a bypass node.
  7925. *
  7926. * @tsl
  7927. * @function
  7928. * @param {Node} outputNode - The output node.
  7929. * @param {Node} callNode - The call node.
  7930. * @returns {BypassNode}
  7931. */
  7932. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  7933. addMethodChaining( 'bypass', bypass );
  7934. /**
  7935. * This node allows to remap a node value from one range into another. E.g a value of
  7936. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7937. * `remap` takes care of that and converts the original value of `0.4` to `0.5`.
  7938. *
  7939. * @tsl
  7940. * @function
  7941. * @param {Node} node - The node that should be remapped.
  7942. * @param {Node} inLowNode - The source or current lower bound of the range.
  7943. * @param {Node} inHighNode - The source or current upper bound of the range.
  7944. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7945. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7946. * @returns {Node}
  7947. */
  7948. const remap = /*@__PURE__*/ Fn( ( [ node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ), doClamp = bool( false ) ] ) => {
  7949. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7950. if ( defined( doClamp ) ) t = t.clamp();
  7951. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7952. } );
  7953. /**
  7954. * This node allows to remap a node value from one range into another but with enabled clamping. E.g a value of
  7955. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7956. * `remapClamp` takes care of that and converts the original value of `0.4` to `0.5`.
  7957. *
  7958. * @tsl
  7959. * @function
  7960. * @param {Node} node - The node that should be remapped.
  7961. * @param {Node} inLowNode - The source or current lower bound of the range.
  7962. * @param {Node} inHighNode - The source or current upper bound of the range.
  7963. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7964. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7965. * @returns {Node}
  7966. */
  7967. function remapClamp( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7968. return remap( node, inLowNode, inHighNode, outLowNode, outHighNode, true );
  7969. }
  7970. addMethodChaining( 'remap', remap );
  7971. addMethodChaining( 'remapClamp', remapClamp );
  7972. /**
  7973. * This class can be used to implement basic expressions in shader code.
  7974. * Basic examples for that are `return`, `continue` or `discard` statements.
  7975. *
  7976. * @augments Node
  7977. */
  7978. class ExpressionNode extends Node {
  7979. static get type() {
  7980. return 'ExpressionNode';
  7981. }
  7982. /**
  7983. * Constructs a new expression node.
  7984. *
  7985. * @param {string} [snippet=''] - The native code snippet.
  7986. * @param {string} [nodeType='void'] - The node type.
  7987. */
  7988. constructor( snippet = '', nodeType = 'void' ) {
  7989. super( nodeType );
  7990. /**
  7991. * The native code snippet.
  7992. *
  7993. * @type {string}
  7994. * @default ''
  7995. */
  7996. this.snippet = snippet;
  7997. }
  7998. generate( builder, output ) {
  7999. const type = this.getNodeType( builder );
  8000. const snippet = this.snippet;
  8001. if ( type === 'void' ) {
  8002. builder.addLineFlowCode( snippet, this );
  8003. } else {
  8004. return builder.format( snippet, type, output );
  8005. }
  8006. }
  8007. }
  8008. /**
  8009. * TSL function for creating an expression node.
  8010. *
  8011. * @tsl
  8012. * @function
  8013. * @param {string} [snippet] - The native code snippet.
  8014. * @param {?string} [nodeType='void'] - The node type.
  8015. * @returns {ExpressionNode}
  8016. */
  8017. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  8018. /**
  8019. * Represents a `discard` shader operation in TSL.
  8020. *
  8021. * @tsl
  8022. * @function
  8023. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  8024. * @return {Node} The `discard` expression.
  8025. */
  8026. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  8027. /**
  8028. * Represents a `return` shader operation in TSL.
  8029. *
  8030. * @tsl
  8031. * @function
  8032. * @return {ExpressionNode} The `return` expression.
  8033. */
  8034. const Return = () => expression( 'return' ).toStack();
  8035. addMethodChaining( 'discard', Discard );
  8036. /**
  8037. * Premultiplies the RGB channels of a color by its alpha channel.
  8038. *
  8039. * This function is useful for converting a non-premultiplied alpha color
  8040. * into a premultiplied alpha format, where the RGB values are scaled
  8041. * by the alpha value. Premultiplied alpha is often used in graphics
  8042. * rendering for certain operations, such as compositing and image processing.
  8043. *
  8044. * @tsl
  8045. * @function
  8046. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  8047. * @return {Node<vec4>} The color with premultiplied alpha.
  8048. */
  8049. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  8050. return vec4( color.rgb.mul( color.a ), color.a );
  8051. }, { color: 'vec4', return: 'vec4' } );
  8052. /**
  8053. * Unpremultiplies the RGB channels of a color by its alpha channel.
  8054. *
  8055. * This function is useful for converting a premultiplied alpha color
  8056. * back into a non-premultiplied alpha format, where the RGB values are
  8057. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  8058. * rendering for certain operations, such as compositing and image processing.
  8059. *
  8060. * @tsl
  8061. * @function
  8062. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  8063. * @return {Node<vec4>} The color with non-premultiplied alpha.
  8064. */
  8065. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  8066. return color.a.equal( 0 ).select( vec4( 0 ), vec4( color.rgb.div( color.a ), color.a ) );
  8067. }, { color: 'vec4', return: 'vec4' } );
  8068. /**
  8069. * Normally, tone mapping and color conversion happens automatically just
  8070. * before outputting a pixel to the default (screen) framebuffer. In certain
  8071. * post processing setups this is too late because some effects such as FXAA
  8072. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  8073. * to apply tone mapping and color space conversion at an arbitrary point
  8074. * in the effect chain.
  8075. *
  8076. * When applying tone mapping and color space conversion manually with this node,
  8077. * you have to set {@link RenderPipeline#outputColorTransform} to `false`.
  8078. *
  8079. * ```js
  8080. * const postProcessing = new RenderPipeline( renderer );
  8081. * postProcessing.outputColorTransform = false;
  8082. *
  8083. * const scenePass = pass( scene, camera );
  8084. * const outputPass = renderOutput( scenePass );
  8085. *
  8086. * postProcessing.outputNode = outputPass;
  8087. * ```
  8088. *
  8089. * @augments TempNode
  8090. */
  8091. class RenderOutputNode extends TempNode {
  8092. static get type() {
  8093. return 'RenderOutputNode';
  8094. }
  8095. /**
  8096. * Constructs a new render output node.
  8097. *
  8098. * @param {Node} colorNode - The color node to process.
  8099. * @param {?number} toneMapping - The tone mapping type.
  8100. * @param {?string} outputColorSpace - The output color space.
  8101. */
  8102. constructor( colorNode, toneMapping, outputColorSpace ) {
  8103. super( 'vec4' );
  8104. /**
  8105. * The color node to process.
  8106. *
  8107. * @type {Node}
  8108. */
  8109. this.colorNode = colorNode;
  8110. /**
  8111. * The tone mapping type.
  8112. *
  8113. * @private
  8114. * @type {?number}
  8115. */
  8116. this._toneMapping = toneMapping;
  8117. /**
  8118. * The output color space.
  8119. *
  8120. * @type {?string}
  8121. */
  8122. this.outputColorSpace = outputColorSpace;
  8123. /**
  8124. * This flag can be used for type testing.
  8125. *
  8126. * @type {boolean}
  8127. * @readonly
  8128. * @default true
  8129. */
  8130. this.isRenderOutputNode = true;
  8131. }
  8132. /**
  8133. * Sets the tone mapping type.
  8134. *
  8135. * @param {number} value - The tone mapping type.
  8136. * @return {ToneMappingNode} A reference to this node.
  8137. */
  8138. setToneMapping( value ) {
  8139. this._toneMapping = value;
  8140. return this;
  8141. }
  8142. /**
  8143. * Gets the tone mapping type.
  8144. *
  8145. * @returns {number} The tone mapping type.
  8146. */
  8147. getToneMapping() {
  8148. return this._toneMapping;
  8149. }
  8150. setup( { context } ) {
  8151. let outputNode = this.colorNode || context.color;
  8152. // clamp alpha
  8153. outputNode = vec4( outputNode.rgb, outputNode.a.clamp( 0.0, 1.0 ) );
  8154. // unpremultiply
  8155. outputNode = unpremultiplyAlpha( outputNode );
  8156. // tone mapping
  8157. const toneMapping = ( this._toneMapping !== null ? this._toneMapping : context.toneMapping ) || NoToneMapping;
  8158. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  8159. if ( toneMapping !== NoToneMapping ) {
  8160. outputNode = outputNode.toneMapping( toneMapping );
  8161. }
  8162. // working to output color space
  8163. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  8164. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  8165. }
  8166. // premultiply in output color space
  8167. outputNode = premultiplyAlpha( outputNode );
  8168. return outputNode;
  8169. }
  8170. }
  8171. /**
  8172. * TSL function for creating a render output node.
  8173. *
  8174. * @tsl
  8175. * @function
  8176. * @param {Node} color - The color node to process.
  8177. * @param {?number} [toneMapping=null] - The tone mapping type.
  8178. * @param {?string} [outputColorSpace=null] - The output color space.
  8179. * @returns {RenderOutputNode}
  8180. */
  8181. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace );
  8182. addMethodChaining( 'renderOutput', renderOutput );
  8183. class DebugNode extends TempNode {
  8184. static get type() {
  8185. return 'DebugNode';
  8186. }
  8187. constructor( node, callback = null ) {
  8188. super();
  8189. this.node = node;
  8190. this.callback = callback;
  8191. }
  8192. generateNodeType( builder ) {
  8193. return this.node.getNodeType( builder );
  8194. }
  8195. setup( builder ) {
  8196. return this.node.build( builder );
  8197. }
  8198. analyze( builder ) {
  8199. return this.node.build( builder );
  8200. }
  8201. generate( builder ) {
  8202. const callback = this.callback;
  8203. const snippet = this.node.build( builder );
  8204. if ( callback !== null ) {
  8205. callback( builder, snippet );
  8206. } else {
  8207. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  8208. const border = '-'.repeat( title.length );
  8209. let code = '';
  8210. code += '// #' + title + '#\n';
  8211. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  8212. code += '/* ... */ ' + snippet + ' /* ... */\n';
  8213. code += '// #' + border + '#\n';
  8214. log$1( code );
  8215. }
  8216. return snippet;
  8217. }
  8218. }
  8219. /**
  8220. * TSL function for creating a debug node.
  8221. *
  8222. * @tsl
  8223. * @function
  8224. * @param {Node} node - The node to debug.
  8225. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  8226. * @returns {DebugNode}
  8227. */
  8228. const debug = ( node, callback = null ) => new DebugNode( nodeObject( node ), callback ).toStack();
  8229. addMethodChaining( 'debug', debug );
  8230. /**
  8231. * InspectorBase is the base class for all inspectors.
  8232. *
  8233. * @class InspectorBase
  8234. * @augments EventDispatcher
  8235. */
  8236. class InspectorBase extends EventDispatcher {
  8237. /**
  8238. * Creates a new InspectorBase.
  8239. */
  8240. constructor() {
  8241. super();
  8242. /**
  8243. * The renderer associated with this inspector.
  8244. *
  8245. * @type {WebGLRenderer}
  8246. * @private
  8247. */
  8248. this._renderer = null;
  8249. /**
  8250. * The current frame being processed.
  8251. *
  8252. * @type {Object}
  8253. */
  8254. this.currentFrame = null;
  8255. }
  8256. /**
  8257. * Returns the node frame for the current renderer.
  8258. *
  8259. * @return {Object} The node frame.
  8260. */
  8261. get nodeFrame() {
  8262. return this._renderer._nodes.nodeFrame;
  8263. }
  8264. /**
  8265. * Sets the renderer for this inspector.
  8266. *
  8267. * @param {WebGLRenderer} renderer - The renderer to associate with this inspector.
  8268. * @return {InspectorBase} This inspector instance.
  8269. */
  8270. setRenderer( renderer ) {
  8271. this._renderer = renderer;
  8272. return this;
  8273. }
  8274. /**
  8275. * Returns the renderer associated with this inspector.
  8276. *
  8277. * @return {WebGLRenderer} The associated renderer.
  8278. */
  8279. getRenderer() {
  8280. return this._renderer;
  8281. }
  8282. /**
  8283. * Initializes the inspector.
  8284. */
  8285. init() { }
  8286. /**
  8287. * Called when a frame begins.
  8288. */
  8289. begin() { }
  8290. /**
  8291. * Called when a frame ends.
  8292. */
  8293. finish() { }
  8294. /**
  8295. * Inspects a node.
  8296. *
  8297. * @param {Node} node - The node to inspect.
  8298. */
  8299. inspect( /*node*/ ) { }
  8300. /**
  8301. * When a compute operation is performed.
  8302. *
  8303. * @param {ComputeNode} computeNode - The compute node being executed.
  8304. * @param {number|Array<number>} dispatchSizeOrCount - The dispatch size or count.
  8305. */
  8306. computeAsync( /*computeNode, dispatchSizeOrCount*/ ) { }
  8307. /**
  8308. * Called when a compute operation begins.
  8309. *
  8310. * @param {string} uid - A unique identifier for the render context.
  8311. * @param {ComputeNode} computeNode - The compute node being executed.
  8312. */
  8313. beginCompute( /*uid, computeNode*/ ) { }
  8314. /**
  8315. * Called when a compute operation ends.
  8316. *
  8317. * @param {string} uid - A unique identifier for the render context.
  8318. * @param {ComputeNode} computeNode - The compute node being executed.
  8319. */
  8320. finishCompute( /*uid*/ ) { }
  8321. /**
  8322. * Called when a render operation begins.
  8323. *
  8324. * @param {string} uid - A unique identifier for the render context.
  8325. * @param {Scene} scene - The scene being rendered.
  8326. * @param {Camera} camera - The camera being used for rendering.
  8327. * @param {?WebGLRenderTarget} renderTarget - The render target, if any.
  8328. */
  8329. beginRender( /*uid, scene, camera, renderTarget*/ ) { }
  8330. /**
  8331. * Called when an animation loop ends.
  8332. *
  8333. * @param {string} uid - A unique identifier for the render context.
  8334. */
  8335. finishRender( /*uid*/ ) { }
  8336. /**
  8337. * Called when a texture copy operation is performed.
  8338. *
  8339. * @param {Texture} srcTexture - The source texture.
  8340. * @param {Texture} dstTexture - The destination texture.
  8341. */
  8342. copyTextureToTexture( /*srcTexture, dstTexture*/ ) { }
  8343. /**
  8344. * Called when a framebuffer copy operation is performed.
  8345. *
  8346. * @param {Texture} framebufferTexture - The texture associated with the framebuffer.
  8347. */
  8348. copyFramebufferToTexture( /*framebufferTexture*/ ) { }
  8349. }
  8350. /**
  8351. * InspectorNode is a wrapper node that allows inspection of node values during rendering.
  8352. * It can be used to debug or analyze node outputs in the rendering pipeline.
  8353. *
  8354. * @augments Node
  8355. */
  8356. class InspectorNode extends Node {
  8357. /**
  8358. * Returns the type of the node.
  8359. *
  8360. * @returns {string}
  8361. */
  8362. static get type() {
  8363. return 'InspectorNode';
  8364. }
  8365. /**
  8366. * Creates an InspectorNode.
  8367. *
  8368. * @param {Node} node - The node to inspect.
  8369. * @param {string} [name=''] - Optional name for the inspector node.
  8370. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  8371. */
  8372. constructor( node, name = '', callback = null ) {
  8373. super();
  8374. this.node = node;
  8375. this.name = name;
  8376. this.callback = callback;
  8377. this.updateType = NodeUpdateType.FRAME;
  8378. this.isInspectorNode = true;
  8379. }
  8380. /**
  8381. * Returns the name of the inspector node.
  8382. *
  8383. * @returns {string}
  8384. */
  8385. getName() {
  8386. return this.name || this.node.name;
  8387. }
  8388. /**
  8389. * Updates the inspector node, allowing inspection of the wrapped node.
  8390. *
  8391. * @param {NodeFrame} frame - A reference to the current node frame.
  8392. */
  8393. update( frame ) {
  8394. frame.renderer.inspector.inspect( this );
  8395. }
  8396. /**
  8397. * Returns the type of the wrapped node.
  8398. *
  8399. * @param {NodeBuilder} builder - The node builder.
  8400. * @returns {string}
  8401. */
  8402. generateNodeType( builder ) {
  8403. return this.node.getNodeType( builder );
  8404. }
  8405. /**
  8406. * Sets up the inspector node.
  8407. *
  8408. * @param {NodeBuilder} builder - The node builder.
  8409. * @returns {Node} The setup node.
  8410. */
  8411. setup( builder ) {
  8412. let node = this.node;
  8413. if ( builder.context.inspector === true && this.callback !== null ) {
  8414. node = this.callback( node );
  8415. }
  8416. if ( builder.renderer.backend.isWebGPUBackend !== true && builder.renderer.inspector.constructor !== InspectorBase ) {
  8417. warnOnce( 'TSL: ".toInspector()" is only available with WebGPU.' );
  8418. }
  8419. return node;
  8420. }
  8421. }
  8422. /**
  8423. * Creates an inspector node to wrap around a given node for inspection purposes.
  8424. *
  8425. * @tsl
  8426. * @param {Node} node - The node to inspect.
  8427. * @param {string} [name=''] - Optional name for the inspector node.
  8428. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  8429. * @returns {Node} The inspector node.
  8430. */
  8431. function inspector( node, name = '', callback = null ) {
  8432. node = nodeObject( node );
  8433. return node.before( new InspectorNode( node, name, callback ) );
  8434. }
  8435. addMethodChaining( 'toInspector', inspector );
  8436. function addNodeElement( name/*, nodeElement*/ ) {
  8437. warn( 'TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  8438. }
  8439. /**
  8440. * Base class for representing shader attributes as nodes.
  8441. *
  8442. * @augments Node
  8443. */
  8444. class AttributeNode extends Node {
  8445. static get type() {
  8446. return 'AttributeNode';
  8447. }
  8448. /**
  8449. * Constructs a new attribute node.
  8450. *
  8451. * @param {string} attributeName - The name of the attribute.
  8452. * @param {?string} nodeType - The node type.
  8453. */
  8454. constructor( attributeName, nodeType = null ) {
  8455. super( nodeType );
  8456. /**
  8457. * `AttributeNode` sets this property to `true` by default.
  8458. *
  8459. * @type {boolean}
  8460. * @default true
  8461. */
  8462. this.global = true;
  8463. this._attributeName = attributeName;
  8464. }
  8465. getHash( builder ) {
  8466. return this.getAttributeName( builder );
  8467. }
  8468. generateNodeType( builder ) {
  8469. let nodeType = this.nodeType;
  8470. if ( nodeType === null ) {
  8471. const attributeName = this.getAttributeName( builder );
  8472. if ( builder.hasGeometryAttribute( attributeName ) ) {
  8473. const attribute = builder.geometry.getAttribute( attributeName );
  8474. nodeType = builder.getTypeFromAttribute( attribute );
  8475. } else {
  8476. nodeType = 'float';
  8477. }
  8478. }
  8479. return nodeType;
  8480. }
  8481. /**
  8482. * Sets the attribute name to the given value. The method can be
  8483. * overwritten in derived classes if the final name must be computed
  8484. * analytically.
  8485. *
  8486. * @param {string} attributeName - The name of the attribute.
  8487. * @return {AttributeNode} A reference to this node.
  8488. */
  8489. setAttributeName( attributeName ) {
  8490. this._attributeName = attributeName;
  8491. return this;
  8492. }
  8493. /**
  8494. * Returns the attribute name of this node. The method can be
  8495. * overwritten in derived classes if the final name must be computed
  8496. * analytically.
  8497. *
  8498. * @param {NodeBuilder} builder - The current node builder.
  8499. * @return {string} The attribute name.
  8500. */
  8501. getAttributeName( /*builder*/ ) {
  8502. return this._attributeName;
  8503. }
  8504. generate( builder ) {
  8505. const attributeName = this.getAttributeName( builder );
  8506. const nodeType = this.getNodeType( builder );
  8507. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  8508. if ( geometryAttribute === true ) {
  8509. const attribute = builder.geometry.getAttribute( attributeName );
  8510. const attributeType = builder.getTypeFromAttribute( attribute );
  8511. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  8512. if ( builder.shaderStage === 'vertex' ) {
  8513. return builder.format( nodeAttribute.name, attributeType, nodeType );
  8514. } else {
  8515. const nodeVarying = varying( this );
  8516. return nodeVarying.build( builder, nodeType );
  8517. }
  8518. } else {
  8519. warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  8520. return builder.generateConst( nodeType );
  8521. }
  8522. }
  8523. serialize( data ) {
  8524. super.serialize( data );
  8525. data.global = this.global;
  8526. data._attributeName = this._attributeName;
  8527. }
  8528. deserialize( data ) {
  8529. super.deserialize( data );
  8530. this.global = data.global;
  8531. this._attributeName = data._attributeName;
  8532. }
  8533. }
  8534. /**
  8535. * TSL function for creating an attribute node.
  8536. *
  8537. * @tsl
  8538. * @function
  8539. * @param {string} name - The name of the attribute.
  8540. * @param {?string} [nodeType=null] - The node type.
  8541. * @returns {AttributeNode}
  8542. */
  8543. const attribute = ( name, nodeType = null ) => new AttributeNode( name, nodeType );
  8544. /**
  8545. * TSL function for creating an uv attribute node with the given index.
  8546. *
  8547. * @tsl
  8548. * @function
  8549. * @param {number} [index=0] - The uv index.
  8550. * @return {AttributeNode<vec2>} The uv attribute node.
  8551. */
  8552. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  8553. /**
  8554. * A node that represents the dimensions of a texture. The texture size is
  8555. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  8556. * or `textureSize()`.
  8557. *
  8558. * @augments Node
  8559. */
  8560. class TextureSizeNode extends Node {
  8561. static get type() {
  8562. return 'TextureSizeNode';
  8563. }
  8564. /**
  8565. * Constructs a new texture size node.
  8566. *
  8567. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  8568. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  8569. */
  8570. constructor( textureNode, levelNode = null ) {
  8571. super( 'uvec2' );
  8572. /**
  8573. * This flag can be used for type testing.
  8574. *
  8575. * @type {boolean}
  8576. * @readonly
  8577. * @default true
  8578. */
  8579. this.isTextureSizeNode = true;
  8580. /**
  8581. * A texture node which size should be retrieved.
  8582. *
  8583. * @type {TextureNode}
  8584. */
  8585. this.textureNode = textureNode;
  8586. /**
  8587. * A level node which defines the requested mip.
  8588. *
  8589. * @type {Node<int>}
  8590. * @default null
  8591. */
  8592. this.levelNode = levelNode;
  8593. }
  8594. generate( builder, output ) {
  8595. const textureProperty = this.textureNode.build( builder, 'property' );
  8596. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  8597. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  8598. }
  8599. }
  8600. /**
  8601. * TSL function for creating a texture size node.
  8602. *
  8603. * @tsl
  8604. * @function
  8605. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  8606. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  8607. * @returns {TextureSizeNode}
  8608. */
  8609. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  8610. /**
  8611. * A special type of uniform node that computes the
  8612. * maximum mipmap level for a given texture node.
  8613. *
  8614. * ```js
  8615. * const level = maxMipLevel( textureNode );
  8616. * ```
  8617. *
  8618. * @augments UniformNode
  8619. */
  8620. class MaxMipLevelNode extends UniformNode {
  8621. static get type() {
  8622. return 'MaxMipLevelNode';
  8623. }
  8624. /**
  8625. * Constructs a new max mip level node.
  8626. *
  8627. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8628. */
  8629. constructor( textureNode ) {
  8630. super( 0 );
  8631. /**
  8632. * The texture node to compute the max mip level for.
  8633. *
  8634. * @private
  8635. * @type {TextureNode}
  8636. */
  8637. this._textureNode = textureNode;
  8638. /**
  8639. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  8640. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  8641. *
  8642. * @type {string}
  8643. * @default 'frame'
  8644. */
  8645. this.updateType = NodeUpdateType.FRAME;
  8646. }
  8647. /**
  8648. * The texture node to compute the max mip level for.
  8649. *
  8650. * @readonly
  8651. * @type {TextureNode}
  8652. */
  8653. get textureNode() {
  8654. return this._textureNode;
  8655. }
  8656. /**
  8657. * The texture.
  8658. *
  8659. * @readonly
  8660. * @type {Texture}
  8661. */
  8662. get texture() {
  8663. return this._textureNode.value;
  8664. }
  8665. update() {
  8666. const texture = this.texture;
  8667. const images = texture.images;
  8668. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  8669. if ( image && image.width !== undefined ) {
  8670. const { width, height } = image;
  8671. this.value = Math.log2( Math.max( width, height ) );
  8672. }
  8673. }
  8674. }
  8675. /**
  8676. * TSL function for creating a max mip level node.
  8677. *
  8678. * @tsl
  8679. * @function
  8680. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8681. * @returns {MaxMipLevelNode}
  8682. */
  8683. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  8684. /**
  8685. * Custom error class for node-related errors, including stack trace information.
  8686. */
  8687. class NodeError extends Error {
  8688. constructor( message, stackTrace = null ) {
  8689. super( message );
  8690. /**
  8691. * The name of the error.
  8692. *
  8693. * @type {string}
  8694. */
  8695. this.name = 'NodeError';
  8696. /**
  8697. * The stack trace associated with the error.
  8698. *
  8699. * @type {?StackTrace}
  8700. */
  8701. this.stackTrace = stackTrace;
  8702. }
  8703. }
  8704. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  8705. /**
  8706. * This type of uniform node represents a 2D texture.
  8707. *
  8708. * @augments UniformNode
  8709. */
  8710. class TextureNode extends UniformNode {
  8711. static get type() {
  8712. return 'TextureNode';
  8713. }
  8714. /**
  8715. * Constructs a new texture node.
  8716. *
  8717. * @param {Texture} [value=EmptyTexture] - The texture.
  8718. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8719. * @param {?Node<int>} [levelNode=null] - The level node.
  8720. * @param {?Node<float>} [biasNode=null] - The bias node.
  8721. */
  8722. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  8723. super( value );
  8724. /**
  8725. * This flag can be used for type testing.
  8726. *
  8727. * @type {boolean}
  8728. * @readonly
  8729. * @default true
  8730. */
  8731. this.isTextureNode = true;
  8732. /**
  8733. * Represents the texture coordinates.
  8734. *
  8735. * @type {?Node<vec2|vec3>}
  8736. * @default null
  8737. */
  8738. this.uvNode = uvNode;
  8739. /**
  8740. * Represents the mip level that should be selected.
  8741. *
  8742. * @type {?Node<int>}
  8743. * @default null
  8744. */
  8745. this.levelNode = levelNode;
  8746. /**
  8747. * Represents the bias to be applied during level-of-detail computation.
  8748. *
  8749. * @type {?Node<float>}
  8750. * @default null
  8751. */
  8752. this.biasNode = biasNode;
  8753. /**
  8754. * Represents a reference value a texture sample is compared to.
  8755. *
  8756. * @type {?Node<float>}
  8757. * @default null
  8758. */
  8759. this.compareNode = null;
  8760. /**
  8761. * When using texture arrays, the depth node defines the layer to select.
  8762. *
  8763. * @type {?Node<int>}
  8764. * @default null
  8765. */
  8766. this.depthNode = null;
  8767. /**
  8768. * When defined, a texture is sampled using explicit gradients.
  8769. *
  8770. * @type {?Array<Node<vec2>>}
  8771. * @default null
  8772. */
  8773. this.gradNode = null;
  8774. /**
  8775. * Represents the optional index constant of the channel to gather.
  8776. * This must be in range [0, 3] and a compile-time constant.
  8777. *
  8778. * @type {?Node<int>}
  8779. * @default null
  8780. */
  8781. this.gatherNode = null;
  8782. /**
  8783. * Represents the optional texel offset applied to the unnormalized texture
  8784. * coordinate before sampling the texture.
  8785. *
  8786. * @type {?Node<ivec2|ivec3>}
  8787. * @default null
  8788. */
  8789. this.offsetNode = null;
  8790. /**
  8791. * Whether texture values should be sampled or fetched.
  8792. *
  8793. * @type {boolean}
  8794. * @default true
  8795. */
  8796. this.sampler = true;
  8797. /**
  8798. * Whether the uv transformation matrix should be
  8799. * automatically updated or not. Use `setUpdateMatrix()`
  8800. * if you want to change the value of the property.
  8801. *
  8802. * @type {boolean}
  8803. * @default false
  8804. */
  8805. this.updateMatrix = false;
  8806. /**
  8807. * By default the `update()` method is not executed. Depending on
  8808. * whether a uv transformation matrix and/or flipY is applied, `update()`
  8809. * is executed per object.
  8810. *
  8811. * @type {string}
  8812. * @default 'none'
  8813. */
  8814. this.updateType = NodeUpdateType.NONE;
  8815. /**
  8816. * The reference node.
  8817. *
  8818. * @type {?Node}
  8819. * @default null
  8820. */
  8821. this.referenceNode = null;
  8822. /**
  8823. * The texture value is stored in a private property.
  8824. *
  8825. * @private
  8826. * @type {Texture}
  8827. */
  8828. this._value = value;
  8829. /**
  8830. * The uniform node that represents the uv transformation matrix.
  8831. *
  8832. * @private
  8833. * @type {?UniformNode<mat3>}
  8834. * @default null
  8835. */
  8836. this._matrixUniform = null;
  8837. /**
  8838. * The uniform node that represents the y-flip. Only required for WebGL.
  8839. *
  8840. * @private
  8841. * @type {?UniformNode<bool>}
  8842. * @default null
  8843. */
  8844. this._flipYUniform = null;
  8845. this.setUpdateMatrix( uvNode === null );
  8846. }
  8847. set value( value ) {
  8848. if ( this.referenceNode ) {
  8849. this.referenceNode.value = value;
  8850. } else {
  8851. this._value = value;
  8852. }
  8853. }
  8854. /**
  8855. * The texture value.
  8856. *
  8857. * @type {Texture}
  8858. */
  8859. get value() {
  8860. return this.referenceNode ? this.referenceNode.value : this._value;
  8861. }
  8862. /**
  8863. * Overwritten since the uniform hash is defined by the texture's UUID.
  8864. *
  8865. * @param {NodeBuilder} builder - The current node builder.
  8866. * @return {string} The uniform hash.
  8867. */
  8868. getUniformHash( /*builder*/ ) {
  8869. return this.value.uuid;
  8870. }
  8871. /**
  8872. * Overwritten since the node type is inferred from the texture type.
  8873. *
  8874. * @param {NodeBuilder} builder - The current node builder.
  8875. * @return {string} The node type.
  8876. */
  8877. generateNodeType( /*builder*/ ) {
  8878. if ( this.value.isDepthTexture === true ) {
  8879. if ( this.gatherNode === null ) return 'float';
  8880. return 'vec4';
  8881. }
  8882. if ( this.value.type === UnsignedIntType ) {
  8883. return 'uvec4';
  8884. } else if ( this.value.type === IntType ) {
  8885. return 'ivec4';
  8886. }
  8887. return 'vec4';
  8888. }
  8889. /**
  8890. * Overwrites the default implementation to return a fixed value `'texture'`.
  8891. *
  8892. * @param {NodeBuilder} builder - The current node builder.
  8893. * @return {string} The input type.
  8894. */
  8895. getInputType( /*builder*/ ) {
  8896. return 'texture';
  8897. }
  8898. /**
  8899. * Returns a default uvs based on the current texture's channel.
  8900. *
  8901. * @return {AttributeNode<vec2>} The default uvs.
  8902. */
  8903. getDefaultUV() {
  8904. return uv$1( this.value.channel );
  8905. }
  8906. /**
  8907. * Overwritten to always return the texture reference of the node.
  8908. *
  8909. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  8910. * @return {Texture} The texture reference.
  8911. */
  8912. updateReference( /*state*/ ) {
  8913. return this.value;
  8914. }
  8915. /**
  8916. * Transforms the given uv node with the texture transformation matrix.
  8917. *
  8918. * @param {Node} uvNode - The uv node to transform.
  8919. * @return {Node} The transformed uv node.
  8920. */
  8921. getTransformedUV( uvNode ) {
  8922. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  8923. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  8924. }
  8925. /**
  8926. * Defines whether the uv transformation matrix should automatically be updated or not.
  8927. *
  8928. * @param {boolean} value - The update toggle.
  8929. * @return {TextureNode} A reference to this node.
  8930. */
  8931. setUpdateMatrix( value ) {
  8932. this.updateMatrix = value;
  8933. return this;
  8934. }
  8935. /**
  8936. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  8937. * to modify the uv node for correct sampling.
  8938. *
  8939. * @param {NodeBuilder} builder - The current node builder.
  8940. * @param {Node} uvNode - The uv node to setup.
  8941. * @return {Node} The updated uv node.
  8942. */
  8943. setupUV( builder, uvNode ) {
  8944. if ( builder.isFlipY() ) {
  8945. if ( this._flipYUniform === null ) this._flipYUniform = uniform( false );
  8946. uvNode = uvNode.toVar();
  8947. if ( this.sampler ) {
  8948. uvNode = this._flipYUniform.select( uvNode.flipY(), uvNode );
  8949. } else {
  8950. uvNode = this._flipYUniform.select( uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) ), uvNode );
  8951. }
  8952. }
  8953. return uvNode;
  8954. }
  8955. /**
  8956. * Setups texture node by preparing the internal nodes for code generation.
  8957. *
  8958. * @param {NodeBuilder} builder - The current node builder.
  8959. */
  8960. setup( builder ) {
  8961. const properties = builder.getNodeProperties( this );
  8962. properties.referenceNode = this.referenceNode;
  8963. //
  8964. const texture = this.value;
  8965. if ( ! texture || texture.isTexture !== true ) {
  8966. throw new NodeError( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().', this.stackTrace );
  8967. }
  8968. //
  8969. const uvNode = Fn( () => {
  8970. let uvNode = this.uvNode;
  8971. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  8972. uvNode = builder.context.getUV( this, builder );
  8973. }
  8974. if ( ! uvNode ) uvNode = this.getDefaultUV();
  8975. if ( this.updateMatrix === true ) {
  8976. uvNode = this.getTransformedUV( uvNode );
  8977. }
  8978. uvNode = this.setupUV( builder, uvNode );
  8979. //
  8980. this.updateType = ( this._matrixUniform !== null || this._flipYUniform !== null ) ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  8981. //
  8982. return uvNode;
  8983. } )();
  8984. //
  8985. let levelNode = this.levelNode;
  8986. if ( levelNode === null && builder.context.getTextureLevel ) {
  8987. levelNode = builder.context.getTextureLevel( this );
  8988. }
  8989. //
  8990. let compareNode = null;
  8991. let compareStepNode = null;
  8992. if ( this.compareNode !== null ) {
  8993. if ( builder.renderer.hasCompatibility( Compatibility.TEXTURE_COMPARE ) ) {
  8994. compareNode = this.compareNode;
  8995. } else {
  8996. const compareFunction = texture.compareFunction;
  8997. if ( compareFunction === null || compareFunction === LessCompare || compareFunction === LessEqualCompare || compareFunction === GreaterCompare || compareFunction === GreaterEqualCompare ) {
  8998. compareStepNode = this.compareNode;
  8999. } else {
  9000. compareNode = this.compareNode;
  9001. warnOnce( 'TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.' );
  9002. }
  9003. }
  9004. }
  9005. properties.uvNode = uvNode;
  9006. properties.levelNode = levelNode;
  9007. properties.biasNode = this.biasNode;
  9008. properties.compareNode = compareNode;
  9009. properties.compareStepNode = compareStepNode;
  9010. properties.gradNode = this.gradNode;
  9011. properties.gatherNode = this.gatherNode;
  9012. properties.depthNode = this.depthNode;
  9013. properties.offsetNode = this.offsetNode;
  9014. }
  9015. /**
  9016. * Generates the uv code snippet.
  9017. *
  9018. * @param {NodeBuilder} builder - The current node builder.
  9019. * @param {Node} uvNode - The uv node to generate code for.
  9020. * @return {string} The generated code snippet.
  9021. */
  9022. generateUV( builder, uvNode ) {
  9023. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  9024. }
  9025. /**
  9026. * Generates the offset code snippet.
  9027. *
  9028. * @param {NodeBuilder} builder - The current node builder.
  9029. * @param {Node} offsetNode - The offset node to generate code for.
  9030. * @return {string} The generated code snippet.
  9031. */
  9032. generateOffset( builder, offsetNode ) {
  9033. return offsetNode.build( builder, 'ivec2' );
  9034. }
  9035. /**
  9036. * Generates the snippet for the texture sampling.
  9037. *
  9038. * @param {NodeBuilder} builder - The current node builder.
  9039. * @param {string} textureProperty - The texture property.
  9040. * @param {string} uvSnippet - The uv snippet.
  9041. * @param {?string} levelSnippet - The level snippet.
  9042. * @param {?string} biasSnippet - The bias snippet.
  9043. * @param {?string} depthSnippet - The depth snippet.
  9044. * @param {?string} compareSnippet - The compare snippet.
  9045. * @param {?Array<string>} gradSnippet - The grad snippet.
  9046. * @param {?string} gatherSnippet - The gather snippet.
  9047. * @param {?string} offsetSnippet - The offset snippet.
  9048. * @param {?string} flipYSnippet - The y-flip snippet. Only used for WebGL.
  9049. * @return {string} The generated code snippet.
  9050. */
  9051. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, gatherSnippet, offsetSnippet, flipYSnippet ) {
  9052. const texture = this.value;
  9053. let snippet;
  9054. if ( biasSnippet ) {
  9055. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet );
  9056. } else if ( gradSnippet ) {
  9057. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet );
  9058. } else if ( gatherSnippet ) {
  9059. if ( compareSnippet ) {
  9060. snippet = builder.generateTextureGatherCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, flipYSnippet );
  9061. } else {
  9062. snippet = builder.generateTextureGather( texture, textureProperty, uvSnippet, gatherSnippet, depthSnippet, offsetSnippet, flipYSnippet );
  9063. }
  9064. } else if ( compareSnippet ) {
  9065. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet );
  9066. } else if ( this.sampler === false ) {
  9067. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  9068. } else if ( levelSnippet ) {
  9069. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  9070. } else {
  9071. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  9072. }
  9073. return snippet;
  9074. }
  9075. /**
  9076. * Generates the code snippet of the texture node.
  9077. *
  9078. * @param {NodeBuilder} builder - The current node builder.
  9079. * @param {string} output - The current output.
  9080. * @return {string} The generated code snippet.
  9081. */
  9082. generate( builder, output ) {
  9083. const texture = this.value;
  9084. const properties = builder.getNodeProperties( this );
  9085. const textureProperty = super.generate( builder, 'property' );
  9086. if ( /^sampler/.test( output ) ) {
  9087. return textureProperty + '_sampler';
  9088. } else if ( builder.isReference( output ) ) {
  9089. return textureProperty;
  9090. } else {
  9091. const nodeData = builder.getDataFromNode( this );
  9092. let nodeType = this.getNodeType( builder );
  9093. let propertyName = nodeData.propertyName;
  9094. if ( propertyName === undefined ) {
  9095. const { uvNode, levelNode, biasNode, compareNode, compareStepNode, depthNode, gradNode, gatherNode, offsetNode } = properties;
  9096. const uvSnippet = this.generateUV( builder, uvNode );
  9097. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  9098. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  9099. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  9100. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  9101. const compareStepSnippet = compareStepNode ? compareStepNode.build( builder, 'float' ) : null;
  9102. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  9103. const gatherSnippet = gatherNode ? gatherNode.build( builder, 'int' ) : null;
  9104. const offsetSnippet = offsetNode ? this.generateOffset( builder, offsetNode ) : null;
  9105. const flipYSnippet = this._flipYUniform ? this._flipYUniform.build( builder, 'bool' ) : null;
  9106. if ( gatherSnippet ) {
  9107. nodeType = 'vec4';
  9108. }
  9109. let finalDepthSnippet = depthSnippet;
  9110. if ( finalDepthSnippet === null && texture.isArrayTexture && this.isTexture3DNode !== true ) {
  9111. finalDepthSnippet = '0';
  9112. }
  9113. const nodeVar = builder.getVarFromNode( this );
  9114. propertyName = builder.getPropertyName( nodeVar );
  9115. let snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, finalDepthSnippet, compareSnippet, gradSnippet, gatherSnippet, offsetSnippet, flipYSnippet );
  9116. if ( compareStepSnippet !== null ) {
  9117. const compareFunction = texture.compareFunction;
  9118. if ( compareFunction === GreaterCompare || compareFunction === GreaterEqualCompare ) {
  9119. snippet = step( expression( snippet, nodeType ), expression( compareStepSnippet, 'float' ) ).build( builder, nodeType );
  9120. } else {
  9121. snippet = step( expression( compareStepSnippet, 'float' ), expression( snippet, nodeType ) ).build( builder, nodeType );
  9122. }
  9123. }
  9124. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  9125. nodeData.snippet = snippet;
  9126. nodeData.propertyName = propertyName;
  9127. }
  9128. let snippet = propertyName;
  9129. if ( builder.needsToWorkingColorSpace( texture ) ) {
  9130. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  9131. }
  9132. return builder.format( snippet, nodeType, output );
  9133. }
  9134. }
  9135. /**
  9136. * Sets the sampler value.
  9137. *
  9138. * @param {boolean} value - The sampler value to set.
  9139. * @return {TextureNode} A reference to this texture node.
  9140. */
  9141. setSampler( value ) {
  9142. this.sampler = value;
  9143. return this;
  9144. }
  9145. /**
  9146. * Returns the sampler value.
  9147. *
  9148. * @return {boolean} The sampler value.
  9149. */
  9150. getSampler() {
  9151. return this.sampler;
  9152. }
  9153. // @TODO: Move to TSL
  9154. /**
  9155. * Samples the texture with the given uv node.
  9156. *
  9157. * @param {Node} uvNode - The uv node.
  9158. * @return {TextureNode} A texture node representing the texture sample.
  9159. */
  9160. sample( uvNode ) {
  9161. const textureNode = this.clone();
  9162. textureNode.uvNode = nodeObject( uvNode );
  9163. textureNode.referenceNode = this.getBase();
  9164. return nodeObject( textureNode );
  9165. }
  9166. /**
  9167. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  9168. *
  9169. * @param {Node<uvec2>} uvNode - The uv node.
  9170. * @returns {TextureNode} A texture node representing the texture load.
  9171. */
  9172. load( uvNode ) {
  9173. return this.sample( uvNode ).setSampler( false );
  9174. }
  9175. /**
  9176. * Samples a blurred version of the texture by defining an internal bias.
  9177. *
  9178. * @param {Node<float>} amountNode - How blurred the texture should be.
  9179. * @return {TextureNode} A texture node representing the texture sample.
  9180. */
  9181. blur( amountNode ) {
  9182. const textureNode = this.clone();
  9183. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  9184. textureNode.referenceNode = this.getBase();
  9185. const map = textureNode.value;
  9186. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  9187. warn( 'TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  9188. textureNode.biasNode = null;
  9189. }
  9190. return nodeObject( textureNode );
  9191. }
  9192. /**
  9193. * Samples a specific mip of the texture.
  9194. *
  9195. * @param {Node<int>} levelNode - The mip level to sample.
  9196. * @return {TextureNode} A texture node representing the texture sample.
  9197. */
  9198. level( levelNode ) {
  9199. const textureNode = this.clone();
  9200. textureNode.levelNode = nodeObject( levelNode );
  9201. textureNode.referenceNode = this.getBase();
  9202. return nodeObject( textureNode );
  9203. }
  9204. /**
  9205. * Returns the texture size of the requested level.
  9206. *
  9207. * @param {Node<int>} levelNode - The level to compute the size for.
  9208. * @return {TextureSizeNode} The texture size.
  9209. */
  9210. size( levelNode ) {
  9211. return textureSize( this, levelNode );
  9212. }
  9213. /**
  9214. * Samples the texture with the given bias.
  9215. *
  9216. * @param {Node<float>} biasNode - The bias node.
  9217. * @return {TextureNode} A texture node representing the texture sample.
  9218. */
  9219. bias( biasNode ) {
  9220. const textureNode = this.clone();
  9221. textureNode.biasNode = nodeObject( biasNode );
  9222. textureNode.referenceNode = this.getBase();
  9223. return nodeObject( textureNode );
  9224. }
  9225. /**
  9226. * Returns the base texture of this node.
  9227. * @return {TextureNode} The base texture node.
  9228. */
  9229. getBase() {
  9230. return this.referenceNode ? this.referenceNode.getBase() : this;
  9231. }
  9232. /**
  9233. * Samples the texture by executing a compare operation.
  9234. *
  9235. * @param {Node<float>} compareNode - The node that defines the compare value.
  9236. * @return {TextureNode} A texture node representing the texture sample.
  9237. */
  9238. compare( compareNode ) {
  9239. const textureNode = this.clone();
  9240. textureNode.compareNode = nodeObject( compareNode );
  9241. textureNode.referenceNode = this.getBase();
  9242. return nodeObject( textureNode );
  9243. }
  9244. /**
  9245. * Samples the texture using an explicit gradient.
  9246. *
  9247. * @param {Node<vec2>} gradNodeX - The gradX node.
  9248. * @param {Node<vec2>} gradNodeY - The gradY node.
  9249. * @return {TextureNode} A texture node representing the texture sample.
  9250. */
  9251. grad( gradNodeX, gradNodeY ) {
  9252. const textureNode = this.clone();
  9253. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  9254. textureNode.referenceNode = this.getBase();
  9255. return nodeObject( textureNode );
  9256. }
  9257. /**
  9258. * Gathers four texels from the texture.
  9259. *
  9260. * @param {Node<int>} gatherNode - The index of the channel to read. This must be in range [0, 3] and a compile-time constant.
  9261. * @return {TextureNode} A texture node representing the texture sample.
  9262. */
  9263. gather( gatherNode = 0 ) {
  9264. const textureNode = this.clone();
  9265. textureNode.gatherNode = nodeObject( gatherNode );
  9266. textureNode.referenceNode = this.getBase();
  9267. return nodeObject( textureNode );
  9268. }
  9269. /**
  9270. * Samples the texture by defining a depth node.
  9271. *
  9272. * @param {Node<int>} depthNode - The depth node.
  9273. * @return {TextureNode} A texture node representing the texture sample.
  9274. */
  9275. depth( depthNode ) {
  9276. const textureNode = this.clone();
  9277. textureNode.depthNode = nodeObject( depthNode );
  9278. textureNode.referenceNode = this.getBase();
  9279. return nodeObject( textureNode );
  9280. }
  9281. /**
  9282. * Samples the texture by defining an offset node.
  9283. *
  9284. * @param {Node<ivec2>} offsetNode - The offset node.
  9285. * @return {TextureNode} A texture node representing the texture sample.
  9286. */
  9287. offset( offsetNode ) {
  9288. const textureNode = this.clone();
  9289. textureNode.offsetNode = nodeObject( offsetNode );
  9290. textureNode.referenceNode = this.getBase();
  9291. return nodeObject( textureNode );
  9292. }
  9293. // --
  9294. serialize( data ) {
  9295. super.serialize( data );
  9296. data.value = this.value.toJSON( data.meta ).uuid;
  9297. data.sampler = this.sampler;
  9298. data.updateMatrix = this.updateMatrix;
  9299. data.updateType = this.updateType;
  9300. }
  9301. deserialize( data ) {
  9302. super.deserialize( data );
  9303. this.value = data.meta.textures[ data.value ];
  9304. this.sampler = data.sampler;
  9305. this.updateMatrix = data.updateMatrix;
  9306. this.updateType = data.updateType;
  9307. }
  9308. /**
  9309. * The update is used to implement the update of the uv transformation matrix.
  9310. */
  9311. update() {
  9312. const texture = this.value;
  9313. const matrixUniform = this._matrixUniform;
  9314. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  9315. if ( texture.matrixAutoUpdate === true ) {
  9316. texture.updateMatrix();
  9317. }
  9318. //
  9319. const flipYUniform = this._flipYUniform;
  9320. if ( flipYUniform !== null ) {
  9321. flipYUniform.value = ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true );
  9322. }
  9323. }
  9324. /**
  9325. * Clones the texture node.
  9326. *
  9327. * @return {TextureNode} The cloned texture node.
  9328. */
  9329. clone() {
  9330. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  9331. newNode.sampler = this.sampler;
  9332. newNode.depthNode = this.depthNode;
  9333. newNode.compareNode = this.compareNode;
  9334. newNode.gradNode = this.gradNode;
  9335. newNode.gatherNode = this.gatherNode;
  9336. newNode.offsetNode = this.offsetNode;
  9337. return newNode;
  9338. }
  9339. }
  9340. /**
  9341. * TSL function for creating a texture node.
  9342. *
  9343. * @tsl
  9344. * @function
  9345. * @param {?Texture} value - The texture.
  9346. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  9347. * @param {?Node<int>} [levelNode=null] - The level node.
  9348. * @param {?Node<float>} [biasNode=null] - The bias node.
  9349. * @returns {TextureNode}
  9350. */
  9351. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  9352. /**
  9353. * TSL function for creating a texture node or sample a texture node already existing.
  9354. *
  9355. * @tsl
  9356. * @function
  9357. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  9358. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  9359. * @param {?Node<int>} [levelNode=null] - The level node.
  9360. * @param {?Node<float>} [biasNode=null] - The bias node.
  9361. * @returns {TextureNode}
  9362. */
  9363. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  9364. let textureNode;
  9365. if ( value && value.isTextureNode === true ) {
  9366. textureNode = nodeObject( value.clone() );
  9367. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  9368. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  9369. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  9370. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  9371. } else {
  9372. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  9373. }
  9374. return textureNode;
  9375. };
  9376. /**
  9377. * TSL function for creating a uniform texture node.
  9378. *
  9379. * @tsl
  9380. * @function
  9381. * @param {?Texture} value - The texture.
  9382. * @returns {TextureNode}
  9383. */
  9384. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  9385. /**
  9386. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  9387. *
  9388. * @tsl
  9389. * @function
  9390. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  9391. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  9392. * @param {?Node<int>} [levelNode=null] - The level node.
  9393. * @param {?Node<float>} [biasNode=null] - The bias node.
  9394. * @returns {TextureNode}
  9395. */
  9396. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  9397. const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  9398. /**
  9399. * Converts a texture or texture node to a sampler.
  9400. *
  9401. * @tsl
  9402. * @function
  9403. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  9404. * @returns {Node}
  9405. */
  9406. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  9407. /**
  9408. * Converts a texture or texture node to a sampler comparison.
  9409. *
  9410. * @tsl
  9411. * @function
  9412. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  9413. * @returns {Node}
  9414. */
  9415. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  9416. /**
  9417. * A special type of uniform node which represents array-like data
  9418. * as uniform buffers. The access usually happens via `element()`
  9419. * which returns an instance of {@link ArrayElementNode}. For example:
  9420. *
  9421. * ```js
  9422. * const bufferNode = buffer( array, 'mat4', count );
  9423. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  9424. * ```
  9425. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  9426. * since it handles more input types and automatically cares about buffer paddings.
  9427. *
  9428. * @augments UniformNode
  9429. */
  9430. class BufferNode extends UniformNode {
  9431. static get type() {
  9432. return 'BufferNode';
  9433. }
  9434. /**
  9435. * Constructs a new buffer node.
  9436. *
  9437. * @param {Array<number>} value - Array-like buffer data.
  9438. * @param {string} bufferType - The data type of the buffer.
  9439. * @param {number} [bufferCount=0] - The count of buffer elements.
  9440. */
  9441. constructor( value, bufferType, bufferCount = 0 ) {
  9442. super( value, bufferType );
  9443. /**
  9444. * This flag can be used for type testing.
  9445. *
  9446. * @type {boolean}
  9447. * @readonly
  9448. * @default true
  9449. */
  9450. this.isBufferNode = true;
  9451. /**
  9452. * The data type of the buffer.
  9453. *
  9454. * @type {string}
  9455. */
  9456. this.bufferType = bufferType;
  9457. /**
  9458. * The uniform node that holds the value of the reference node.
  9459. *
  9460. * @type {number}
  9461. * @default 0
  9462. */
  9463. this.bufferCount = bufferCount;
  9464. /**
  9465. * An array of update ranges.
  9466. *
  9467. * @type {Array<{start: number, count: number}>}
  9468. */
  9469. this.updateRanges = [];
  9470. }
  9471. /**
  9472. * Adds a range of data in the data array to be updated on the GPU.
  9473. *
  9474. * @param {number} start - Position at which to start update.
  9475. * @param {number} count - The number of components to update.
  9476. */
  9477. addUpdateRange( start, count ) {
  9478. this.updateRanges.push( { start, count } );
  9479. }
  9480. /**
  9481. * Clears the update ranges.
  9482. */
  9483. clearUpdateRanges() {
  9484. this.updateRanges.length = 0;
  9485. }
  9486. /**
  9487. * The data type of the buffer elements.
  9488. *
  9489. * @param {NodeBuilder} builder - The current node builder.
  9490. * @return {string} The element type.
  9491. */
  9492. getElementType( builder ) {
  9493. return this.getNodeType( builder );
  9494. }
  9495. /**
  9496. * Overwrites the default implementation to return a fixed value `'buffer'`.
  9497. *
  9498. * @param {NodeBuilder} builder - The current node builder.
  9499. * @return {string} The input type.
  9500. */
  9501. getInputType( /*builder*/ ) {
  9502. return 'buffer';
  9503. }
  9504. }
  9505. /**
  9506. * TSL function for creating a buffer node.
  9507. *
  9508. * @tsl
  9509. * @function
  9510. * @param {Array<number>} value - Array-like buffer data.
  9511. * @param {string} type - The data type of a buffer element.
  9512. * @param {number} count - The count of buffer elements.
  9513. * @returns {BufferNode}
  9514. */
  9515. const buffer = ( value, type, count ) => new BufferNode( value, type, count );
  9516. /**
  9517. * Represents the element access on uniform array nodes.
  9518. *
  9519. * @augments ArrayElementNode
  9520. */
  9521. class UniformArrayElementNode extends ArrayElementNode {
  9522. static get type() {
  9523. return 'UniformArrayElementNode';
  9524. }
  9525. /**
  9526. * Constructs a new buffer node.
  9527. *
  9528. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  9529. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  9530. */
  9531. constructor( uniformArrayNode, indexNode ) {
  9532. super( uniformArrayNode, indexNode );
  9533. /**
  9534. * This flag can be used for type testing.
  9535. *
  9536. * @type {boolean}
  9537. * @readonly
  9538. * @default true
  9539. */
  9540. this.isArrayBufferElementNode = true;
  9541. }
  9542. generate( builder ) {
  9543. const snippet = super.generate( builder );
  9544. const type = this.getNodeType( builder );
  9545. const paddedType = this.node.getPaddedType();
  9546. return builder.format( snippet, paddedType, type );
  9547. }
  9548. }
  9549. /**
  9550. * Similar to {@link BufferNode} this module represents array-like data as
  9551. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  9552. * data types in the array (e.g `three.js` primitives) and automatically
  9553. * manage buffer padding. It should be the first choice when working with
  9554. * uniforms buffers.
  9555. * ```js
  9556. * const tintColors = uniformArray( [
  9557. * new Color( 1, 0, 0 ),
  9558. * new Color( 0, 1, 0 ),
  9559. * new Color( 0, 0, 1 )
  9560. * ], 'color' );
  9561. *
  9562. * const redColor = tintColors.element( 0 );
  9563. *
  9564. * @augments BufferNode
  9565. */
  9566. class UniformArrayNode extends BufferNode {
  9567. static get type() {
  9568. return 'UniformArrayNode';
  9569. }
  9570. /**
  9571. * Constructs a new uniform array node.
  9572. *
  9573. * @param {Array<any>} value - Array holding the buffer data.
  9574. * @param {?string} [elementType=null] - The data type of a buffer element.
  9575. */
  9576. constructor( value, elementType = null ) {
  9577. super( null );
  9578. /**
  9579. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  9580. * hold number primitives as well as three.js objects like vectors, matrices
  9581. * or colors.
  9582. *
  9583. * @type {Array<any>}
  9584. */
  9585. this.array = value;
  9586. /**
  9587. * The data type of an array element.
  9588. *
  9589. * @type {string}
  9590. */
  9591. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  9592. /**
  9593. * The padded type. Uniform buffers must conform to a certain buffer layout
  9594. * so a separate type is computed to ensure correct buffer size.
  9595. *
  9596. * @type {string}
  9597. */
  9598. this.paddedType = this.getPaddedType();
  9599. /**
  9600. * Overwritten since uniform array nodes are updated per render.
  9601. *
  9602. * @type {string}
  9603. * @default 'render'
  9604. */
  9605. this.updateType = NodeUpdateType.RENDER;
  9606. /**
  9607. * This flag can be used for type testing.
  9608. *
  9609. * @type {boolean}
  9610. * @readonly
  9611. * @default true
  9612. */
  9613. this.isArrayBufferNode = true;
  9614. }
  9615. /**
  9616. * This method is overwritten since the node type is inferred from the
  9617. * {@link UniformArrayNode#paddedType}.
  9618. *
  9619. * @param {NodeBuilder} builder - The current node builder.
  9620. * @return {string} The node type.
  9621. */
  9622. generateNodeType( /*builder*/ ) {
  9623. return this.paddedType;
  9624. }
  9625. /**
  9626. * The data type of the array elements.
  9627. *
  9628. * @param {NodeBuilder} builder - The current node builder.
  9629. * @return {string} The element type.
  9630. */
  9631. getElementType() {
  9632. return this.elementType;
  9633. }
  9634. /**
  9635. * Returns the padded type based on the element type.
  9636. *
  9637. * @return {string} The padded type.
  9638. */
  9639. getPaddedType() {
  9640. const elementType = this.elementType;
  9641. let paddedType = 'vec4';
  9642. if ( elementType === 'mat2' ) {
  9643. paddedType = 'mat2';
  9644. } else if ( /mat/.test( elementType ) === true ) {
  9645. paddedType = 'mat4';
  9646. } else if ( elementType.charAt( 0 ) === 'i' ) {
  9647. paddedType = 'ivec4';
  9648. } else if ( elementType.charAt( 0 ) === 'u' ) {
  9649. paddedType = 'uvec4';
  9650. }
  9651. return paddedType;
  9652. }
  9653. /**
  9654. * The update makes sure to correctly transfer the data from the (complex) objects
  9655. * in the array to the internal, correctly padded value buffer.
  9656. *
  9657. * @param {NodeFrame} frame - A reference to the current node frame.
  9658. */
  9659. update( /*frame*/ ) {
  9660. const { array, value } = this;
  9661. const elementType = this.elementType;
  9662. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  9663. for ( let i = 0; i < array.length; i ++ ) {
  9664. const index = i * 4;
  9665. value[ index ] = array[ i ];
  9666. }
  9667. } else if ( elementType === 'color' ) {
  9668. for ( let i = 0; i < array.length; i ++ ) {
  9669. const index = i * 4;
  9670. const vector = array[ i ];
  9671. value[ index ] = vector.r;
  9672. value[ index + 1 ] = vector.g;
  9673. value[ index + 2 ] = vector.b || 0;
  9674. //value[ index + 3 ] = vector.a || 0;
  9675. }
  9676. } else if ( elementType === 'mat2' ) {
  9677. for ( let i = 0; i < array.length; i ++ ) {
  9678. const index = i * 4;
  9679. const matrix = array[ i ];
  9680. value[ index ] = matrix.elements[ 0 ];
  9681. value[ index + 1 ] = matrix.elements[ 1 ];
  9682. value[ index + 2 ] = matrix.elements[ 2 ];
  9683. value[ index + 3 ] = matrix.elements[ 3 ];
  9684. }
  9685. } else if ( elementType === 'mat3' ) {
  9686. for ( let i = 0; i < array.length; i ++ ) {
  9687. const index = i * 16;
  9688. const matrix = array[ i ];
  9689. value[ index ] = matrix.elements[ 0 ];
  9690. value[ index + 1 ] = matrix.elements[ 1 ];
  9691. value[ index + 2 ] = matrix.elements[ 2 ];
  9692. value[ index + 4 ] = matrix.elements[ 3 ];
  9693. value[ index + 5 ] = matrix.elements[ 4 ];
  9694. value[ index + 6 ] = matrix.elements[ 5 ];
  9695. value[ index + 8 ] = matrix.elements[ 6 ];
  9696. value[ index + 9 ] = matrix.elements[ 7 ];
  9697. value[ index + 10 ] = matrix.elements[ 8 ];
  9698. value[ index + 15 ] = 1;
  9699. }
  9700. } else if ( elementType === 'mat4' ) {
  9701. for ( let i = 0; i < array.length; i ++ ) {
  9702. const index = i * 16;
  9703. const matrix = array[ i ];
  9704. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  9705. value[ index + i ] = matrix.elements[ i ];
  9706. }
  9707. }
  9708. } else {
  9709. for ( let i = 0; i < array.length; i ++ ) {
  9710. const index = i * 4;
  9711. const vector = array[ i ];
  9712. value[ index ] = vector.x;
  9713. value[ index + 1 ] = vector.y;
  9714. value[ index + 2 ] = vector.z || 0;
  9715. value[ index + 3 ] = vector.w || 0;
  9716. }
  9717. }
  9718. }
  9719. /**
  9720. * Implement the value buffer creation based on the array data.
  9721. *
  9722. * @param {NodeBuilder} builder - A reference to the current node builder.
  9723. * @return {null}
  9724. */
  9725. setup( builder ) {
  9726. const length = this.array.length;
  9727. const elementType = this.elementType;
  9728. let arrayType = Float32Array;
  9729. const paddedType = this.paddedType;
  9730. const paddedElementLength = builder.getTypeLength( paddedType );
  9731. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  9732. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  9733. this.value = new arrayType( length * paddedElementLength );
  9734. this.bufferCount = length;
  9735. this.bufferType = paddedType;
  9736. this.update(); // initialize the buffer values
  9737. return super.setup( builder );
  9738. }
  9739. /**
  9740. * Overwrites the default `element()` method to provide element access
  9741. * based on {@link UniformArrayNode}.
  9742. *
  9743. * @param {IndexNode} indexNode - The index node.
  9744. * @return {UniformArrayElementNode}
  9745. */
  9746. element( indexNode ) {
  9747. return new UniformArrayElementNode( this, nodeObject( indexNode ) );
  9748. }
  9749. }
  9750. /**
  9751. * TSL function for creating an uniform array node.
  9752. *
  9753. * @tsl
  9754. * @function
  9755. * @param {Array<any>} values - Array-like data.
  9756. * @param {?string} [nodeType] - The data type of the array elements.
  9757. * @returns {UniformArrayNode}
  9758. */
  9759. const uniformArray = ( values, nodeType ) => new UniformArrayNode( values, nodeType );
  9760. /**
  9761. * The node allows to set values for built-in shader variables. That is
  9762. * required for features like hardware-accelerated vertex clipping.
  9763. *
  9764. * @augments Node
  9765. */
  9766. class BuiltinNode extends Node {
  9767. /**
  9768. * Constructs a new builtin node.
  9769. *
  9770. * @param {string} name - The name of the built-in shader variable.
  9771. */
  9772. constructor( name ) {
  9773. super( 'float' );
  9774. /**
  9775. * The name of the built-in shader variable.
  9776. *
  9777. * @type {string}
  9778. */
  9779. this.name = name;
  9780. /**
  9781. * This flag can be used for type testing.
  9782. *
  9783. * @type {boolean}
  9784. * @readonly
  9785. * @default true
  9786. */
  9787. this.isBuiltinNode = true;
  9788. }
  9789. /**
  9790. * Generates the code snippet of the builtin node.
  9791. *
  9792. * @param {NodeBuilder} builder - The current node builder.
  9793. * @return {string} The generated code snippet.
  9794. */
  9795. generate( /* builder */ ) {
  9796. return this.name;
  9797. }
  9798. }
  9799. /**
  9800. * TSL function for creating a builtin node.
  9801. *
  9802. * @tsl
  9803. * @function
  9804. * @param {string} name - The name of the built-in shader variable.
  9805. * @returns {BuiltinNode}
  9806. */
  9807. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  9808. let _screenSizeVec, _viewportVec;
  9809. /**
  9810. * This node provides a collection of screen related metrics.
  9811. * Depending on {@link ScreenNode#scope}, the nodes can represent
  9812. * resolution or viewport data as well as fragment or uv coordinates.
  9813. *
  9814. * @augments Node
  9815. */
  9816. class ScreenNode extends Node {
  9817. static get type() {
  9818. return 'ScreenNode';
  9819. }
  9820. /**
  9821. * Constructs a new screen node.
  9822. *
  9823. * @param {('coordinate'|'viewport'|'size'|'uv'|'dpr')} scope - The node's scope.
  9824. */
  9825. constructor( scope ) {
  9826. super();
  9827. /**
  9828. * The node represents different metric depending on which scope is selected.
  9829. *
  9830. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  9831. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  9832. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  9833. * - `ScreenNode.UV`: Normalized coordinates.
  9834. * - `ScreenNode.DPR`: Device pixel ratio.
  9835. *
  9836. * @type {('coordinate'|'viewport'|'size'|'uv'|'dpr')}
  9837. */
  9838. this.scope = scope;
  9839. /**
  9840. * This output node.
  9841. *
  9842. * @private
  9843. * @type {?Node}
  9844. * @default null
  9845. */
  9846. this._output = null;
  9847. /**
  9848. * This flag can be used for type testing.
  9849. *
  9850. * @type {boolean}
  9851. * @readonly
  9852. * @default true
  9853. */
  9854. this.isViewportNode = true;
  9855. }
  9856. /**
  9857. * This method is overwritten since the node type depends on the selected scope.
  9858. *
  9859. * @return {('float'|'vec2'|'vec4')} The node type.
  9860. */
  9861. generateNodeType() {
  9862. if ( this.scope === ScreenNode.DPR ) return 'float';
  9863. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  9864. else return 'vec2';
  9865. }
  9866. /**
  9867. * This method is overwritten since the node's update type depends on the selected scope.
  9868. *
  9869. * @return {NodeUpdateType} The update type.
  9870. */
  9871. getUpdateType() {
  9872. let updateType = NodeUpdateType.NONE;
  9873. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT || this.scope === ScreenNode.DPR ) {
  9874. updateType = NodeUpdateType.RENDER;
  9875. }
  9876. this.updateType = updateType;
  9877. return updateType;
  9878. }
  9879. /**
  9880. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  9881. * from the current renderer.
  9882. *
  9883. * @param {NodeFrame} frame - A reference to the current node frame.
  9884. */
  9885. update( { renderer } ) {
  9886. const renderTarget = renderer.getRenderTarget();
  9887. if ( this.scope === ScreenNode.VIEWPORT ) {
  9888. if ( renderTarget !== null ) {
  9889. _viewportVec.copy( renderTarget.viewport );
  9890. } else {
  9891. renderer.getViewport( _viewportVec );
  9892. _viewportVec.multiplyScalar( renderer.getPixelRatio() );
  9893. }
  9894. } else if ( this.scope === ScreenNode.DPR ) {
  9895. this._output.value = renderer.getPixelRatio();
  9896. } else {
  9897. if ( renderTarget !== null ) {
  9898. _screenSizeVec.width = renderTarget.width;
  9899. _screenSizeVec.height = renderTarget.height;
  9900. } else {
  9901. renderer.getDrawingBufferSize( _screenSizeVec );
  9902. }
  9903. }
  9904. }
  9905. setup( /*builder*/ ) {
  9906. const scope = this.scope;
  9907. let output = null;
  9908. if ( scope === ScreenNode.SIZE ) {
  9909. output = uniform( _screenSizeVec || ( _screenSizeVec = new Vector2() ) );
  9910. } else if ( scope === ScreenNode.VIEWPORT ) {
  9911. output = uniform( _viewportVec || ( _viewportVec = new Vector4() ) );
  9912. } else if ( scope === ScreenNode.DPR ) {
  9913. output = uniform( 1 );
  9914. } else {
  9915. output = vec2( screenCoordinate.div( screenSize ) );
  9916. }
  9917. this._output = output;
  9918. return output;
  9919. }
  9920. generate( builder ) {
  9921. if ( this.scope === ScreenNode.COORDINATE ) {
  9922. let coord = builder.getFragCoord();
  9923. if ( builder.isFlipY() ) {
  9924. // follow webgpu standards
  9925. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  9926. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  9927. }
  9928. return coord;
  9929. }
  9930. return super.generate( builder );
  9931. }
  9932. }
  9933. ScreenNode.COORDINATE = 'coordinate';
  9934. ScreenNode.VIEWPORT = 'viewport';
  9935. ScreenNode.SIZE = 'size';
  9936. ScreenNode.UV = 'uv';
  9937. ScreenNode.DPR = 'dpr';
  9938. // Screen
  9939. /**
  9940. * TSL object that represents the current DPR.
  9941. *
  9942. * @tsl
  9943. * @type {ScreenNode<float>}
  9944. */
  9945. const screenDPR = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.DPR );
  9946. /**
  9947. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  9948. *
  9949. * @tsl
  9950. * @type {ScreenNode<vec2>}
  9951. */
  9952. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  9953. /**
  9954. * TSL object that represents the screen resolution in physical pixel units.
  9955. *
  9956. * @tsl
  9957. * @type {ScreenNode<vec2>}
  9958. */
  9959. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  9960. /**
  9961. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  9962. *
  9963. * @tsl
  9964. * @type {ScreenNode<vec2>}
  9965. */
  9966. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  9967. // Viewport
  9968. /**
  9969. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  9970. *
  9971. * @tsl
  9972. * @type {ScreenNode<vec4>}
  9973. */
  9974. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  9975. /**
  9976. * TSL object that represents the viewport resolution in physical pixel units.
  9977. *
  9978. * @tsl
  9979. * @type {ScreenNode<vec2>}
  9980. */
  9981. const viewportSize = viewport.zw;
  9982. /**
  9983. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  9984. *
  9985. * @tsl
  9986. * @type {ScreenNode<vec2>}
  9987. */
  9988. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  9989. /**
  9990. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  9991. *
  9992. * @tsl
  9993. * @type {ScreenNode<vec2>}
  9994. */
  9995. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  9996. // Deprecated
  9997. /**
  9998. * @deprecated since r169. Use {@link screenSize} instead.
  9999. */
  10000. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  10001. warn( 'TSL: "viewportResolution" is deprecated. Use "screenSize" instead.', new StackTrace() );
  10002. return screenSize;
  10003. }, 'vec2' ).once() )();
  10004. // Cache node uniforms
  10005. let _cameraProjectionMatrixBase = null;
  10006. let _cameraProjectionMatrixArray = null;
  10007. let _cameraProjectionMatrixInverseBase = null;
  10008. let _cameraProjectionMatrixInverseArray = null;
  10009. let _cameraViewMatrixBase = null;
  10010. let _cameraViewMatrixArray = null;
  10011. let _cameraWorldMatrixBase = null;
  10012. let _cameraWorldMatrixArray = null;
  10013. let _cameraNormalMatrixBase = null;
  10014. let _cameraNormalMatrixArray = null;
  10015. let _cameraPositionBase = null;
  10016. let _cameraPositionArray = null;
  10017. let _cameraViewportBase = null;
  10018. let _cameraViewportArray = null;
  10019. /**
  10020. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  10021. *
  10022. * @tsl
  10023. * @type {UniformNode<uint>}
  10024. */
  10025. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  10026. /**
  10027. * TSL object that represents the `near` value of the camera used for the current render.
  10028. *
  10029. * @tsl
  10030. * @type {UniformNode<float>}
  10031. */
  10032. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  10033. /**
  10034. * TSL object that represents the `far` value of the camera used for the current render.
  10035. *
  10036. * @tsl
  10037. * @type {UniformNode<float>}
  10038. */
  10039. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  10040. /**
  10041. * TSL object that represents the projection matrix of the camera used for the current render.
  10042. *
  10043. * @tsl
  10044. * @type {UniformNode<mat4>}
  10045. */
  10046. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  10047. let cameraProjectionMatrix;
  10048. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  10049. const matrices = [];
  10050. for ( const subCamera of camera.cameras ) {
  10051. matrices.push( subCamera.projectionMatrix );
  10052. }
  10053. if ( _cameraProjectionMatrixArray === null ) {
  10054. _cameraProjectionMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  10055. } else {
  10056. _cameraProjectionMatrixArray.array = matrices;
  10057. }
  10058. cameraProjectionMatrix = _cameraProjectionMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  10059. } else {
  10060. if ( _cameraProjectionMatrixBase === null ) {
  10061. _cameraProjectionMatrixBase = uniform( camera.projectionMatrix ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  10062. }
  10063. cameraProjectionMatrix = _cameraProjectionMatrixBase;
  10064. }
  10065. return cameraProjectionMatrix;
  10066. } ).once() )();
  10067. /**
  10068. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  10069. *
  10070. * @tsl
  10071. * @type {UniformNode<mat4>}
  10072. */
  10073. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  10074. let cameraProjectionMatrixInverse;
  10075. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  10076. const matrices = [];
  10077. for ( const subCamera of camera.cameras ) {
  10078. matrices.push( subCamera.projectionMatrixInverse );
  10079. }
  10080. if ( _cameraProjectionMatrixInverseArray === null ) {
  10081. _cameraProjectionMatrixInverseArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  10082. } else {
  10083. _cameraProjectionMatrixInverseArray.array = matrices;
  10084. }
  10085. cameraProjectionMatrixInverse = _cameraProjectionMatrixInverseArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  10086. } else {
  10087. if ( _cameraProjectionMatrixInverseBase === null ) {
  10088. _cameraProjectionMatrixInverseBase = uniform( camera.projectionMatrixInverse ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  10089. }
  10090. cameraProjectionMatrixInverse = _cameraProjectionMatrixInverseBase;
  10091. }
  10092. return cameraProjectionMatrixInverse;
  10093. } ).once() )();
  10094. /**
  10095. * TSL object that represents the view matrix of the camera used for the current render.
  10096. *
  10097. * @tsl
  10098. * @type {UniformNode<mat4>}
  10099. */
  10100. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  10101. let cameraViewMatrix;
  10102. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  10103. const matrices = [];
  10104. for ( const subCamera of camera.cameras ) {
  10105. matrices.push( subCamera.matrixWorldInverse );
  10106. }
  10107. if ( _cameraViewMatrixArray === null ) {
  10108. _cameraViewMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  10109. } else {
  10110. _cameraViewMatrixArray.array = matrices;
  10111. }
  10112. cameraViewMatrix = _cameraViewMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  10113. } else {
  10114. if ( _cameraViewMatrixBase === null ) {
  10115. _cameraViewMatrixBase = uniform( camera.matrixWorldInverse ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  10116. }
  10117. cameraViewMatrix = _cameraViewMatrixBase;
  10118. }
  10119. return cameraViewMatrix;
  10120. } ).once() )();
  10121. /**
  10122. * TSL object that represents the world matrix of the camera used for the current render.
  10123. *
  10124. * @tsl
  10125. * @type {UniformNode<mat4>}
  10126. */
  10127. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  10128. let cameraWorldMatrix;
  10129. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  10130. const matrices = [];
  10131. for ( const subCamera of camera.cameras ) {
  10132. matrices.push( subCamera.matrixWorld );
  10133. }
  10134. if ( _cameraWorldMatrixArray === null ) {
  10135. _cameraWorldMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  10136. } else {
  10137. _cameraWorldMatrixArray.array = matrices;
  10138. }
  10139. cameraWorldMatrix = _cameraWorldMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  10140. } else {
  10141. if ( _cameraWorldMatrixBase === null ) {
  10142. _cameraWorldMatrixBase = uniform( camera.matrixWorld ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  10143. }
  10144. cameraWorldMatrix = _cameraWorldMatrixBase;
  10145. }
  10146. return cameraWorldMatrix;
  10147. } ).once() )();
  10148. /**
  10149. * TSL object that represents the normal matrix of the camera used for the current render.
  10150. *
  10151. * @tsl
  10152. * @type {UniformNode<mat3>}
  10153. */
  10154. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  10155. let cameraNormalMatrix;
  10156. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  10157. const matrices = [];
  10158. for ( const subCamera of camera.cameras ) {
  10159. matrices.push( subCamera.normalMatrix );
  10160. }
  10161. if ( _cameraNormalMatrixArray === null ) {
  10162. _cameraNormalMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  10163. } else {
  10164. _cameraNormalMatrixArray.array = matrices;
  10165. }
  10166. cameraNormalMatrix = _cameraNormalMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  10167. } else {
  10168. if ( _cameraNormalMatrixBase === null ) {
  10169. _cameraNormalMatrixBase = uniform( camera.normalMatrix ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  10170. }
  10171. cameraNormalMatrix = _cameraNormalMatrixBase;
  10172. }
  10173. return cameraNormalMatrix;
  10174. } ).once() )();
  10175. /**
  10176. * TSL object that represents the position in world space of the camera used for the current render.
  10177. *
  10178. * @tsl
  10179. * @type {UniformNode<vec3>}
  10180. */
  10181. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  10182. let cameraPosition;
  10183. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  10184. const positions = [];
  10185. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  10186. positions.push( new Vector3() );
  10187. }
  10188. if ( _cameraPositionArray === null ) {
  10189. _cameraPositionArray = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  10190. const subCameras = camera.cameras;
  10191. const array = self.array;
  10192. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  10193. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  10194. }
  10195. } );
  10196. } else {
  10197. _cameraPositionArray.array = positions;
  10198. }
  10199. cameraPosition = _cameraPositionArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  10200. } else {
  10201. if ( _cameraPositionBase === null ) {
  10202. _cameraPositionBase = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  10203. }
  10204. cameraPosition = _cameraPositionBase;
  10205. }
  10206. return cameraPosition;
  10207. } ).once() )();
  10208. /**
  10209. * TSL object that represents the viewport of the camera used for the current render.
  10210. *
  10211. * @tsl
  10212. * @type {UniformNode<vec4>}
  10213. */
  10214. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  10215. let cameraViewport;
  10216. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  10217. const viewports = [];
  10218. for ( const subCamera of camera.cameras ) {
  10219. viewports.push( subCamera.viewport );
  10220. }
  10221. if ( _cameraViewportArray === null ) {
  10222. _cameraViewportArray = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  10223. } else {
  10224. _cameraViewportArray.array = viewports;
  10225. }
  10226. cameraViewport = _cameraViewportArray.element( cameraIndex ).toConst( 'cameraViewport' );
  10227. } else {
  10228. if ( _cameraViewportBase === null ) {
  10229. // Fallback for single camera
  10230. _cameraViewportBase = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  10231. }
  10232. cameraViewport = _cameraViewportBase;
  10233. }
  10234. return cameraViewport;
  10235. } ).once() )();
  10236. const _sphere = /*@__PURE__*/ new Sphere();
  10237. /**
  10238. * This node can be used to access transformation related metrics of 3D objects.
  10239. * Depending on the selected scope, a different metric is represented as a uniform
  10240. * in the shader. The following scopes are supported:
  10241. *
  10242. * - `POSITION`: The object's position in world space.
  10243. * - `VIEW_POSITION`: The object's position in view/camera space.
  10244. * - `DIRECTION`: The object's direction in world space.
  10245. * - `SCALE`: The object's scale in world space.
  10246. * - `WORLD_MATRIX`: The object's matrix in world space.
  10247. *
  10248. * @augments Node
  10249. */
  10250. class Object3DNode extends Node {
  10251. static get type() {
  10252. return 'Object3DNode';
  10253. }
  10254. /**
  10255. * Constructs a new object 3D node.
  10256. *
  10257. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  10258. * @param {?Object3D} [object3d=null] - The 3D object.
  10259. */
  10260. constructor( scope, object3d = null ) {
  10261. super();
  10262. /**
  10263. * The node reports a different type of transformation depending on the scope.
  10264. *
  10265. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  10266. */
  10267. this.scope = scope;
  10268. /**
  10269. * The 3D object.
  10270. *
  10271. * @type {?Object3D}
  10272. * @default null
  10273. */
  10274. this.object3d = object3d;
  10275. /**
  10276. * Overwritten since this type of node is updated per object.
  10277. *
  10278. * @type {string}
  10279. * @default 'object'
  10280. */
  10281. this.updateType = NodeUpdateType.OBJECT;
  10282. /**
  10283. * Holds the value of the node as a uniform.
  10284. *
  10285. * @type {UniformNode}
  10286. */
  10287. this.uniformNode = new UniformNode( null );
  10288. }
  10289. /**
  10290. * Overwritten since the node type is inferred from the scope.
  10291. *
  10292. * @return {('mat4'|'vec3'|'float')} The node type.
  10293. */
  10294. generateNodeType() {
  10295. const scope = this.scope;
  10296. if ( scope === Object3DNode.WORLD_MATRIX ) {
  10297. return 'mat4';
  10298. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  10299. return 'vec3';
  10300. } else if ( scope === Object3DNode.RADIUS ) {
  10301. return 'float';
  10302. }
  10303. }
  10304. /**
  10305. * Updates the uniform value depending on the scope.
  10306. *
  10307. * @param {NodeFrame} frame - The current node frame.
  10308. */
  10309. update( frame ) {
  10310. const object = this.object3d;
  10311. const uniformNode = this.uniformNode;
  10312. const scope = this.scope;
  10313. if ( scope === Object3DNode.WORLD_MATRIX ) {
  10314. uniformNode.value = object.matrixWorld;
  10315. } else if ( scope === Object3DNode.POSITION ) {
  10316. uniformNode.value = uniformNode.value || new Vector3();
  10317. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  10318. } else if ( scope === Object3DNode.SCALE ) {
  10319. uniformNode.value = uniformNode.value || new Vector3();
  10320. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  10321. } else if ( scope === Object3DNode.DIRECTION ) {
  10322. uniformNode.value = uniformNode.value || new Vector3();
  10323. object.getWorldDirection( uniformNode.value );
  10324. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  10325. const camera = frame.camera;
  10326. uniformNode.value = uniformNode.value || new Vector3();
  10327. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  10328. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  10329. } else if ( scope === Object3DNode.RADIUS ) {
  10330. const geometry = frame.object.geometry;
  10331. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10332. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  10333. uniformNode.value = _sphere.radius;
  10334. }
  10335. }
  10336. /**
  10337. * Generates the code snippet of the uniform node. The node type of the uniform
  10338. * node also depends on the selected scope.
  10339. *
  10340. * @param {NodeBuilder} builder - The current node builder.
  10341. * @return {string} The generated code snippet.
  10342. */
  10343. generate( builder ) {
  10344. const scope = this.scope;
  10345. if ( scope === Object3DNode.WORLD_MATRIX ) {
  10346. this.uniformNode.nodeType = 'mat4';
  10347. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  10348. this.uniformNode.nodeType = 'vec3';
  10349. } else if ( scope === Object3DNode.RADIUS ) {
  10350. this.uniformNode.nodeType = 'float';
  10351. }
  10352. return this.uniformNode.build( builder );
  10353. }
  10354. serialize( data ) {
  10355. super.serialize( data );
  10356. data.scope = this.scope;
  10357. }
  10358. deserialize( data ) {
  10359. super.deserialize( data );
  10360. this.scope = data.scope;
  10361. }
  10362. }
  10363. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  10364. Object3DNode.POSITION = 'position';
  10365. Object3DNode.SCALE = 'scale';
  10366. Object3DNode.VIEW_POSITION = 'viewPosition';
  10367. Object3DNode.DIRECTION = 'direction';
  10368. Object3DNode.RADIUS = 'radius';
  10369. /**
  10370. * TSL function for creating an object 3D node that represents the object's direction in world space.
  10371. *
  10372. * @tsl
  10373. * @function
  10374. * @param {?Object3D} [object3d] - The 3D object.
  10375. * @returns {Object3DNode<vec3>}
  10376. */
  10377. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  10378. /**
  10379. * TSL function for creating an object 3D node that represents the object's world matrix.
  10380. *
  10381. * @tsl
  10382. * @function
  10383. * @param {?Object3D} [object3d] - The 3D object.
  10384. * @returns {Object3DNode<mat4>}
  10385. */
  10386. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  10387. /**
  10388. * TSL function for creating an object 3D node that represents the object's position in world space.
  10389. *
  10390. * @tsl
  10391. * @function
  10392. * @param {?Object3D} [object3d] - The 3D object.
  10393. * @returns {Object3DNode<vec3>}
  10394. */
  10395. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  10396. /**
  10397. * TSL function for creating an object 3D node that represents the object's scale in world space.
  10398. *
  10399. * @tsl
  10400. * @function
  10401. * @param {?Object3D} [object3d] - The 3D object.
  10402. * @returns {Object3DNode<vec3>}
  10403. */
  10404. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  10405. /**
  10406. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  10407. *
  10408. * @tsl
  10409. * @function
  10410. * @param {?Object3D} [object3d] - The 3D object.
  10411. * @returns {Object3DNode<vec3>}
  10412. */
  10413. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  10414. /**
  10415. * TSL function for creating an object 3D node that represents the object's radius.
  10416. *
  10417. * @tsl
  10418. * @function
  10419. * @param {?Object3D} [object3d] - The 3D object.
  10420. * @returns {Object3DNode<float>}
  10421. */
  10422. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  10423. /**
  10424. * This type of node is a specialized version of `Object3DNode`
  10425. * with larger set of model related metrics. Unlike `Object3DNode`,
  10426. * `ModelNode` extracts the reference to the 3D object from the
  10427. * current node frame state.
  10428. *
  10429. * @augments Object3DNode
  10430. */
  10431. class ModelNode extends Object3DNode {
  10432. static get type() {
  10433. return 'ModelNode';
  10434. }
  10435. /**
  10436. * Constructs a new object model node.
  10437. *
  10438. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  10439. */
  10440. constructor( scope ) {
  10441. super( scope );
  10442. }
  10443. /**
  10444. * Extracts the model reference from the frame state and then
  10445. * updates the uniform value depending on the scope.
  10446. *
  10447. * @param {NodeFrame} frame - The current node frame.
  10448. */
  10449. update( frame ) {
  10450. this.object3d = frame.object;
  10451. super.update( frame );
  10452. }
  10453. }
  10454. /**
  10455. * TSL object that represents the object's direction in world space.
  10456. *
  10457. * @tsl
  10458. * @type {ModelNode<vec3>}
  10459. */
  10460. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  10461. /**
  10462. * TSL object that represents the object's world matrix.
  10463. *
  10464. * @tsl
  10465. * @type {ModelNode<mat4>}
  10466. */
  10467. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  10468. /**
  10469. * TSL object that represents the object's position in world space.
  10470. *
  10471. * @tsl
  10472. * @type {ModelNode<vec3>}
  10473. */
  10474. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  10475. /**
  10476. * TSL object that represents the object's scale in world space.
  10477. *
  10478. * @tsl
  10479. * @type {ModelNode<vec3>}
  10480. */
  10481. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  10482. /**
  10483. * TSL object that represents the object's position in view/camera space.
  10484. *
  10485. * @tsl
  10486. * @type {ModelNode<vec3>}
  10487. */
  10488. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  10489. /**
  10490. * TSL object that represents the object's radius.
  10491. *
  10492. * @tsl
  10493. * @type {ModelNode<float>}
  10494. */
  10495. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  10496. /**
  10497. * TSL object that represents the object's normal matrix.
  10498. *
  10499. * @tsl
  10500. * @type {UniformNode<mat3>}
  10501. */
  10502. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  10503. /**
  10504. * TSL object that represents the object's inverse world matrix.
  10505. *
  10506. * @tsl
  10507. * @type {UniformNode<mat4>}
  10508. */
  10509. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  10510. /**
  10511. * TSL object that represents the object's model view matrix.
  10512. *
  10513. * @tsl
  10514. * @type {Node<mat4>}
  10515. */
  10516. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  10517. return builder.context.modelViewMatrix || mediumpModelViewMatrix;
  10518. } ).once() )().toVar( 'modelViewMatrix' );
  10519. // GPU Precision
  10520. /**
  10521. * TSL object that represents the object's model view in `mediump` precision.
  10522. *
  10523. * @tsl
  10524. * @type {Node<mat4>}
  10525. */
  10526. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  10527. // CPU Precision
  10528. /**
  10529. * TSL object that represents the object's model view in `highp` precision
  10530. * which is achieved by computing the matrix in JS and not in the shader.
  10531. *
  10532. * @tsl
  10533. * @type {Node<mat4>}
  10534. */
  10535. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  10536. builder.context.isHighPrecisionModelViewMatrix = true;
  10537. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  10538. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  10539. } );
  10540. } ).once() )().toVar( 'highpModelViewMatrix' );
  10541. /**
  10542. * TSL object that represents the object's model normal view in `highp` precision
  10543. * which is achieved by computing the matrix in JS and not in the shader.
  10544. *
  10545. * @tsl
  10546. * @type {Node<mat3>}
  10547. */
  10548. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  10549. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  10550. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  10551. if ( isHighPrecisionModelViewMatrix !== true ) {
  10552. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  10553. }
  10554. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  10555. } );
  10556. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  10557. /**
  10558. * TSL object that represents the clip space position of the current rendered object.
  10559. *
  10560. * @tsl
  10561. * @type {VaryingNode<vec4>}
  10562. */
  10563. const clipSpace = /*@__PURE__*/ ( Fn( ( builder ) => {
  10564. if ( builder.shaderStage !== 'fragment' ) {
  10565. warnOnce( 'TSL: `clipSpace` is only available in fragment stage.' );
  10566. return vec4();
  10567. }
  10568. return builder.context.clipSpace.toVarying( 'v_clipSpace' );
  10569. } ).once() )();
  10570. /**
  10571. * TSL object that represents the position attribute of the current rendered object.
  10572. *
  10573. * @tsl
  10574. * @type {AttributeNode<vec3>}
  10575. */
  10576. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  10577. /**
  10578. * TSL object that represents the transformed vertex position in local space of the current rendered object.
  10579. *
  10580. * The term "transformed" indicates that an object or material's properties, such as skinning, batch,
  10581. * instancing, or displacement mapping, will change the vertex position of the node when present.
  10582. * To use the pre-transformed local space position of the object, use {@link positionGeometry}.
  10583. *
  10584. * @tsl
  10585. * @type {AttributeNode<vec3>}
  10586. */
  10587. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  10588. /**
  10589. * TSL object that represents the previous vertex position in local space of the current rendered object.
  10590. * Used in context of {@link VelocityNode} for rendering motion vectors.
  10591. *
  10592. * @tsl
  10593. * @type {AttributeNode<vec3>}
  10594. */
  10595. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  10596. /**
  10597. * TSL object that represents the vertex position in world space of the current rendered object.
  10598. *
  10599. * @tsl
  10600. * @type {VaryingNode<vec3>}
  10601. */
  10602. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  10603. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  10604. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  10605. /**
  10606. * TSL object that represents the position world direction of the current rendered object.
  10607. *
  10608. * @tsl
  10609. * @type {Node<vec3>}
  10610. */
  10611. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  10612. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  10613. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  10614. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  10615. /**
  10616. * TSL object that represents the vertex position in view space of the current rendered object.
  10617. *
  10618. * @tsl
  10619. * @type {VaryingNode<vec3>}
  10620. */
  10621. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  10622. if ( builder.shaderStage === 'fragment' && builder.material.vertexNode ) {
  10623. // reconstruct view position from clip space
  10624. const viewPos = cameraProjectionMatrixInverse.mul( clipSpace );
  10625. return viewPos.xyz.div( viewPos.w ).toVar( 'positionView' );
  10626. }
  10627. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  10628. }, 'vec3' ).once( [ 'POSITION', 'VERTEX' ] ) )();
  10629. /**
  10630. * TSL object that represents the position view direction of the current rendered object.
  10631. *
  10632. * @tsl
  10633. * @type {VaryingNode<vec3>}
  10634. */
  10635. const positionViewDirection = /*@__PURE__*/ ( Fn( ( builder ) => {
  10636. let output;
  10637. if ( builder.camera.isOrthographicCamera ) {
  10638. output = vec3( 0, 0, 1 );
  10639. } else {
  10640. output = positionView.negate().toVarying( 'v_positionViewDirection' ).normalize();
  10641. }
  10642. return output.toVar( 'positionViewDirection' );
  10643. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  10644. /**
  10645. * This node can be used to evaluate whether a primitive is front or back facing.
  10646. *
  10647. * @augments Node
  10648. */
  10649. class FrontFacingNode extends Node {
  10650. static get type() {
  10651. return 'FrontFacingNode';
  10652. }
  10653. /**
  10654. * Constructs a new front facing node.
  10655. */
  10656. constructor() {
  10657. super( 'bool' );
  10658. /**
  10659. * This flag can be used for type testing.
  10660. *
  10661. * @type {boolean}
  10662. * @readonly
  10663. * @default true
  10664. */
  10665. this.isFrontFacingNode = true;
  10666. }
  10667. generate( builder ) {
  10668. if ( builder.shaderStage !== 'fragment' ) return 'true';
  10669. //
  10670. const { material } = builder;
  10671. if ( material.side === BackSide ) {
  10672. return 'false';
  10673. }
  10674. return builder.getFrontFacing();
  10675. }
  10676. }
  10677. /**
  10678. * TSL object that represents whether a primitive is front or back facing
  10679. *
  10680. * @tsl
  10681. * @type {FrontFacingNode<bool>}
  10682. */
  10683. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  10684. /**
  10685. * TSL object that represents the front facing status as a number instead of a bool.
  10686. * `1` means front facing, `-1` means back facing.
  10687. *
  10688. * @tsl
  10689. * @type {Node<float>}
  10690. */
  10691. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  10692. /**
  10693. * Negates a vector if the rendering occurs on the back side of a face,
  10694. * based on the material's side configuration.
  10695. *
  10696. * - If the material's side is `BackSide`, the vector is inverted (negated).
  10697. * - If the material's side is `DoubleSide`, the vector is multiplied by `faceDirection`
  10698. * (negated only for back-facing fragments).
  10699. * - If the material's side is `FrontSide` (default), the vector remains unchanged.
  10700. *
  10701. * @tsl
  10702. * @function
  10703. * @param {Node<vec3>} vector - The vector to process.
  10704. * @returns {Node<vec3>} The processed vector.
  10705. */
  10706. const negateOnBackSide = /*@__PURE__*/ Fn( ( [ vector ], { material } ) => {
  10707. const side = material.side;
  10708. if ( side === BackSide ) {
  10709. vector = vector.mul( -1 );
  10710. } else if ( side === DoubleSide ) {
  10711. vector = vector.mul( faceDirection );
  10712. }
  10713. return vector;
  10714. } );
  10715. /**
  10716. * Negates a vector if the rendering occurs on the back side of a face,
  10717. * based on the material's side configuration.
  10718. *
  10719. * - If the material's side is `BackSide`, the vector is inverted (negated).
  10720. * - If the material's side is `DoubleSide`, the vector is multiplied by `faceDirection`
  10721. * (negated only for back-facing fragments).
  10722. * - If the material's side is `FrontSide` (default), the vector remains unchanged.
  10723. *
  10724. * @tsl
  10725. * @function
  10726. * @deprecated since r185. Use {@link negateOnBackSide} instead.
  10727. * @param {Node<vec3>} vector - The vector to convert.
  10728. * @returns {Node<vec3>} The converted vector.
  10729. */
  10730. const directionToFaceDirection = ( vector ) => {
  10731. warnOnce( 'TSL: "directionToFaceDirection()" has been renamed to "negateOnBackSide()".' ); // @deprecated r185
  10732. return negateOnBackSide( vector );
  10733. };
  10734. /**
  10735. * TSL object that represents the normal attribute of the current rendered object in local space.
  10736. *
  10737. * @tsl
  10738. * @type {Node<vec3>}
  10739. */
  10740. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  10741. /**
  10742. * TSL object that represents the vertex normal of the current rendered object in local space.
  10743. *
  10744. * @tsl
  10745. * @type {Node<vec3>}
  10746. */
  10747. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  10748. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  10749. warn( 'TSL: Vertex attribute "normal" not found on geometry.' );
  10750. return vec3( 0, 1, 0 );
  10751. }
  10752. return normalGeometry;
  10753. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  10754. /**
  10755. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  10756. *
  10757. * @tsl
  10758. * @type {Node<vec3>}
  10759. */
  10760. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  10761. /**
  10762. * TSL object that represents the vertex normal of the current rendered object in view space.
  10763. *
  10764. * @tsl
  10765. * @type {Node<vec3>}
  10766. */
  10767. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  10768. let node;
  10769. if ( builder.isFlatShading() ) {
  10770. node = normalFlat;
  10771. } else {
  10772. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  10773. }
  10774. return node;
  10775. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  10776. /**
  10777. * TSL object that represents the vertex normal of the current rendered object in world space.
  10778. *
  10779. * @tsl
  10780. * @type {Node<vec3>}
  10781. */
  10782. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  10783. let normal = normalViewGeometry.transformNormalByInverseViewMatrix( cameraViewMatrix );
  10784. if ( builder.isFlatShading() !== true ) {
  10785. normal = normal.toVarying( 'v_normalWorldGeometry' );
  10786. }
  10787. return normal.normalize().toVar( 'normalWorldGeometry' );
  10788. }, 'vec3' ).once() )();
  10789. /**
  10790. * TSL object that represents the vertex normal of the current rendered object in view space.
  10791. *
  10792. * @tsl
  10793. * @type {Node<vec3>}
  10794. */
  10795. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  10796. let node;
  10797. if ( builder.subBuildFn === 'NORMAL' || builder.subBuildFn === 'VERTEX' ) {
  10798. node = normalViewGeometry;
  10799. if ( builder.isFlatShading() !== true ) {
  10800. node = negateOnBackSide( node );
  10801. }
  10802. } else {
  10803. // Use custom context to avoid side effects from nodes overwriting getUV, getTextureLevel in the context (e.g. EnvironmentNode)
  10804. node = builder.context.setupNormal().context( { getUV: null, getTextureLevel: null } );
  10805. }
  10806. return node;
  10807. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  10808. /**
  10809. * TSL object that represents the vertex normal of the current rendered object in world space.
  10810. *
  10811. * @tsl
  10812. * @type {Node<vec3>}
  10813. */
  10814. const normalWorld = /*@__PURE__*/ normalView.transformNormalByInverseViewMatrix( cameraViewMatrix ).toVar( 'normalWorld' );
  10815. /**
  10816. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  10817. *
  10818. * @tsl
  10819. * @type {Node<vec3>}
  10820. */
  10821. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  10822. let node;
  10823. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  10824. node = normalView;
  10825. } else {
  10826. // Use custom context to avoid side effects from nodes overwriting getUV, getTextureLevel in the context (e.g. EnvironmentNode)
  10827. node = context.setupClearcoatNormal().context( { getUV: null, getTextureLevel: null } );
  10828. }
  10829. return node;
  10830. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  10831. /**
  10832. * Transforms the normal by the normal matrix of the given matrix and then normalizes the result.
  10833. *
  10834. * @tsl
  10835. * @function
  10836. * @param {Node<vec3>} normal - The normal.
  10837. * @param {Node<mat3|mat4>} [matrix=modelWorldMatrix] - The matrix.
  10838. * @return {Node<vec3>} The transformed normal.
  10839. */
  10840. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  10841. const normalMatrix = mat3( matrix ).inverse().transpose();
  10842. return normalMatrix.mul( normal ).normalize();
  10843. } );
  10844. addMethodChaining( 'transformNormal', transformNormal );
  10845. /**
  10846. * Transforms the given normal from local to view space.
  10847. *
  10848. * @tsl
  10849. * @function
  10850. * @param {Node<vec3>} normal - The normal.
  10851. * @param {NodeBuilder} builder - The current node builder.
  10852. * @return {Node<vec3>} The transformed normal.
  10853. */
  10854. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  10855. const modelNormalViewMatrix = builder.context.modelNormalViewMatrix;
  10856. if ( modelNormalViewMatrix ) {
  10857. return normal.transformNormalByViewMatrix( modelNormalViewMatrix );
  10858. }
  10859. //
  10860. const transformedNormal = modelNormalMatrix.mul( normal );
  10861. return transformedNormal.transformNormalByViewMatrix( cameraViewMatrix );
  10862. } );
  10863. // Deprecated
  10864. /**
  10865. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  10866. *
  10867. * @tsl
  10868. * @type {Node<vec3>}
  10869. * @deprecated since r178. Use `normalView` instead.
  10870. */
  10871. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  10872. warn( 'TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  10873. return normalView;
  10874. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10875. /**
  10876. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  10877. *
  10878. * @tsl
  10879. * @type {Node<vec3>}
  10880. * @deprecated since r178. Use `normalWorld` instead.
  10881. */
  10882. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  10883. warn( 'TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  10884. return normalWorld;
  10885. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10886. /**
  10887. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  10888. *
  10889. * @tsl
  10890. * @type {Node<vec3>}
  10891. * @deprecated since r178. Use `clearcoatNormalView` instead.
  10892. */
  10893. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  10894. warn( 'TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  10895. return clearcoatNormalView;
  10896. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10897. const _m1$1 = /*@__PURE__*/ new Matrix4();
  10898. /**
  10899. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  10900. *
  10901. * @tsl
  10902. * @type {UniformNode<float>}
  10903. */
  10904. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  10905. /**
  10906. * TSL object that represents the intensity of environment maps of PBR materials.
  10907. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  10908. *
  10909. * @tsl
  10910. * @type {Node<float>}
  10911. */
  10912. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  10913. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  10914. } );
  10915. /**
  10916. * TSL object that represents the rotation of environment maps.
  10917. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  10918. * rotation of `scene.environment` instead.
  10919. *
  10920. * @tsl
  10921. * @type {Node<mat4>}
  10922. */
  10923. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  10924. return frame.material;
  10925. } ).onObjectUpdate( function ( { material, scene } ) {
  10926. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  10927. if ( rotation ) {
  10928. // note: since the matrix is orthonormal, we can use the more-efficient transpose() in lieu of invert()
  10929. _m1$1.makeRotationFromEuler( rotation ).transpose();
  10930. } else {
  10931. _m1$1.identity();
  10932. }
  10933. return _m1$1;
  10934. } );
  10935. /**
  10936. * The reflect vector in view space.
  10937. *
  10938. * @tsl
  10939. * @type {Node<vec3>}
  10940. */
  10941. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  10942. /**
  10943. * The refract vector in view space.
  10944. *
  10945. * @tsl
  10946. * @type {Node<vec3>}
  10947. */
  10948. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  10949. /**
  10950. * Used for sampling cube maps when using cube reflection mapping.
  10951. *
  10952. * @tsl
  10953. * @type {Node<vec3>}
  10954. */
  10955. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraWorldMatrix ).toVar( 'reflectVector' );
  10956. /**
  10957. * Used for sampling cube maps when using cube refraction mapping.
  10958. *
  10959. * @tsl
  10960. * @type {Node<vec3>}
  10961. */
  10962. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraWorldMatrix ).toVar( 'refractVector' );
  10963. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  10964. /**
  10965. * This type of uniform node represents a cube texture.
  10966. *
  10967. * @augments TextureNode
  10968. */
  10969. class CubeTextureNode extends TextureNode {
  10970. static get type() {
  10971. return 'CubeTextureNode';
  10972. }
  10973. /**
  10974. * Constructs a new cube texture node.
  10975. *
  10976. * @param {CubeTexture} value - The cube texture.
  10977. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10978. * @param {?Node<int>} [levelNode=null] - The level node.
  10979. * @param {?Node<float>} [biasNode=null] - The bias node.
  10980. */
  10981. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  10982. super( value, uvNode, levelNode, biasNode );
  10983. /**
  10984. * This flag can be used for type testing.
  10985. *
  10986. * @type {boolean}
  10987. * @readonly
  10988. * @default true
  10989. */
  10990. this.isCubeTextureNode = true;
  10991. }
  10992. /**
  10993. * Overwrites the default implementation to return the appropriate cube texture type.
  10994. *
  10995. * @param {NodeBuilder} builder - The current node builder.
  10996. * @return {string} The input type.
  10997. */
  10998. getInputType( /*builder*/ ) {
  10999. if ( this.value.isDepthTexture === true ) {
  11000. return 'cubeDepthTexture';
  11001. }
  11002. return 'cubeTexture';
  11003. }
  11004. /**
  11005. * Returns a default uvs based on the mapping type of the cube texture.
  11006. *
  11007. * @return {Node<vec3>} The default uv attribute.
  11008. */
  11009. getDefaultUV() {
  11010. const texture = this.value;
  11011. if ( texture.mapping === CubeReflectionMapping ) {
  11012. return reflectVector;
  11013. } else if ( texture.mapping === CubeRefractionMapping ) {
  11014. return refractVector;
  11015. } else {
  11016. error( 'CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  11017. return vec3( 0, 0, 0 );
  11018. }
  11019. }
  11020. /**
  11021. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  11022. * for cube textures. The uv transformation matrix is not applied to cube textures.
  11023. *
  11024. * @param {boolean} value - The update toggle.
  11025. */
  11026. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  11027. /**
  11028. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  11029. * to modify the uv node for correct sampling.
  11030. *
  11031. * @param {NodeBuilder} builder - The current node builder.
  11032. * @param {Node} uvNode - The uv node to setup.
  11033. * @return {Node} The updated uv node.
  11034. */
  11035. setupUV( builder, uvNode ) {
  11036. const texture = this.value;
  11037. // Depth textures (shadow maps) - no environment rotation, Y flip for WebGPU
  11038. if ( texture.isDepthTexture === true ) {
  11039. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  11040. return vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  11041. }
  11042. return uvNode;
  11043. }
  11044. // rotate first
  11045. uvNode = materialEnvRotation.mul( uvNode );
  11046. // flip
  11047. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  11048. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  11049. }
  11050. return uvNode;
  11051. }
  11052. /**
  11053. * Generates the uv code snippet.
  11054. *
  11055. * @param {NodeBuilder} builder - The current node builder.
  11056. * @param {Node} cubeUV - The uv node to generate code for.
  11057. * @return {string} The generated code snippet.
  11058. */
  11059. generateUV( builder, cubeUV ) {
  11060. return cubeUV.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  11061. }
  11062. }
  11063. /**
  11064. * TSL function for creating a cube texture node.
  11065. *
  11066. * @tsl
  11067. * @function
  11068. * @param {CubeTexture} value - The cube texture.
  11069. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  11070. * @param {?Node<int>} [levelNode=null] - The level node.
  11071. * @param {?Node<float>} [biasNode=null] - The bias node.
  11072. * @returns {CubeTextureNode}
  11073. */
  11074. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  11075. /**
  11076. * TSL function for creating a cube texture uniform node.
  11077. *
  11078. * @tsl
  11079. * @function
  11080. * @param {?(CubeTexture|CubeTextureNode)} [value=EmptyTexture] - The cube texture.
  11081. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  11082. * @param {?Node<int>} [levelNode=null] - The level node.
  11083. * @param {?Node<float>} [biasNode=null] - The bias node.
  11084. * @returns {CubeTextureNode}
  11085. */
  11086. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  11087. let textureNode;
  11088. if ( value && value.isCubeTextureNode === true ) {
  11089. textureNode = nodeObject( value.clone() );
  11090. textureNode.referenceNode = value; // Ensure the reference is set to the original node
  11091. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  11092. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  11093. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  11094. } else {
  11095. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  11096. }
  11097. return textureNode;
  11098. };
  11099. /**
  11100. * TSL function for creating a uniform cube texture node.
  11101. *
  11102. * @tsl
  11103. * @function
  11104. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  11105. * @returns {CubeTextureNode}
  11106. */
  11107. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  11108. // TODO: Avoid duplicated code and use only ReferenceBaseNode or ReferenceNode
  11109. /**
  11110. * This class is only relevant if the referenced property is array-like.
  11111. * In this case, `ReferenceElementNode` allows to refer to a specific
  11112. * element inside the data structure via an index.
  11113. *
  11114. * @augments ArrayElementNode
  11115. */
  11116. class ReferenceElementNode extends ArrayElementNode {
  11117. static get type() {
  11118. return 'ReferenceElementNode';
  11119. }
  11120. /**
  11121. * Constructs a new reference element node.
  11122. *
  11123. * @param {?ReferenceNode} referenceNode - The reference node.
  11124. * @param {Node} indexNode - The index node that defines the element access.
  11125. */
  11126. constructor( referenceNode, indexNode ) {
  11127. super( referenceNode, indexNode );
  11128. /**
  11129. * Similar to {@link ReferenceNode#reference}, an additional
  11130. * property references to the current node.
  11131. *
  11132. * @type {?ReferenceNode}
  11133. * @default null
  11134. */
  11135. this.referenceNode = referenceNode;
  11136. /**
  11137. * This flag can be used for type testing.
  11138. *
  11139. * @type {boolean}
  11140. * @readonly
  11141. * @default true
  11142. */
  11143. this.isReferenceElementNode = true;
  11144. }
  11145. /**
  11146. * This method is overwritten since the node type is inferred from
  11147. * the uniform type of the reference node.
  11148. *
  11149. * @return {string} The node type.
  11150. */
  11151. generateNodeType() {
  11152. return this.referenceNode.uniformType;
  11153. }
  11154. generate( builder ) {
  11155. const snippet = super.generate( builder );
  11156. const arrayType = this.referenceNode.getNodeType( builder );
  11157. const elementType = this.getNodeType( builder );
  11158. return builder.format( snippet, arrayType, elementType );
  11159. }
  11160. }
  11161. /**
  11162. * This type of node establishes a reference to a property of another object.
  11163. * In this way, the value of the node is automatically linked to the value of
  11164. * referenced object. Reference nodes internally represent the linked value
  11165. * as a uniform.
  11166. *
  11167. * @augments Node
  11168. */
  11169. class ReferenceNode extends Node {
  11170. static get type() {
  11171. return 'ReferenceNode';
  11172. }
  11173. /**
  11174. * Constructs a new reference node.
  11175. *
  11176. * @param {string} property - The name of the property the node refers to.
  11177. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  11178. * @param {?Object} [object=null] - The object the property belongs to.
  11179. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  11180. */
  11181. constructor( property, uniformType, object = null, count = null ) {
  11182. super();
  11183. /**
  11184. * The name of the property the node refers to.
  11185. *
  11186. * @type {string}
  11187. */
  11188. this.property = property;
  11189. /**
  11190. * The uniform type that should be used to represent the property value.
  11191. *
  11192. * @type {string}
  11193. */
  11194. this.uniformType = uniformType;
  11195. /**
  11196. * The object the property belongs to.
  11197. *
  11198. * @type {?Object}
  11199. * @default null
  11200. */
  11201. this.object = object;
  11202. /**
  11203. * When the linked property is an array, this parameter defines its length.
  11204. *
  11205. * @type {?number}
  11206. * @default null
  11207. */
  11208. this.count = count;
  11209. /**
  11210. * The property name might have dots so nested properties can be referred.
  11211. * The hierarchy of the names is stored inside this array.
  11212. *
  11213. * @type {Array<string>}
  11214. */
  11215. this.properties = property.split( '.' );
  11216. /**
  11217. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  11218. * since the final reference might be updated from calling code.
  11219. *
  11220. * @type {?Object}
  11221. * @default null
  11222. */
  11223. this.reference = object;
  11224. /**
  11225. * The uniform node that holds the value of the reference node.
  11226. *
  11227. * @type {UniformNode}
  11228. * @default null
  11229. */
  11230. this.node = null;
  11231. /**
  11232. * The uniform group of the internal uniform.
  11233. *
  11234. * @type {UniformGroupNode}
  11235. * @default null
  11236. */
  11237. this.group = null;
  11238. /**
  11239. * An optional label of the internal uniform node.
  11240. *
  11241. * @type {?string}
  11242. * @default null
  11243. */
  11244. this.name = null;
  11245. /**
  11246. * Overwritten since reference nodes are updated per object.
  11247. *
  11248. * @type {string}
  11249. * @default 'object'
  11250. */
  11251. this.updateType = NodeUpdateType.OBJECT;
  11252. }
  11253. /**
  11254. * When the referred property is array-like, this method can be used
  11255. * to access elements via an index node.
  11256. *
  11257. * @param {IndexNode} indexNode - indexNode.
  11258. * @return {ReferenceElementNode} A reference to an element.
  11259. */
  11260. element( indexNode ) {
  11261. return new ReferenceElementNode( this, nodeObject( indexNode ) );
  11262. }
  11263. /**
  11264. * Sets the uniform group for this reference node.
  11265. *
  11266. * @param {UniformGroupNode} group - The uniform group to set.
  11267. * @return {ReferenceNode} A reference to this node.
  11268. */
  11269. setGroup( group ) {
  11270. this.group = group;
  11271. return this;
  11272. }
  11273. /**
  11274. * Sets the name for the internal uniform.
  11275. *
  11276. * @param {string} name - The label to set.
  11277. * @return {ReferenceNode} A reference to this node.
  11278. */
  11279. setName( name ) {
  11280. this.name = name;
  11281. return this;
  11282. }
  11283. /**
  11284. * Sets the label for the internal uniform.
  11285. *
  11286. * @deprecated
  11287. * @param {string} name - The label to set.
  11288. * @return {ReferenceNode} A reference to this node.
  11289. */
  11290. label( name ) {
  11291. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  11292. return this.setName( name );
  11293. }
  11294. /**
  11295. * Sets the node type which automatically defines the internal
  11296. * uniform type.
  11297. *
  11298. * @param {string} uniformType - The type to set.
  11299. */
  11300. setNodeType( uniformType ) {
  11301. let node = null;
  11302. if ( this.count !== null ) {
  11303. node = buffer( null, uniformType, this.count );
  11304. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  11305. node = uniformArray( null, uniformType );
  11306. node.updateType = NodeUpdateType.OBJECT;
  11307. } else if ( uniformType === 'texture' ) {
  11308. node = texture( null );
  11309. } else if ( uniformType === 'cubeTexture' ) {
  11310. node = cubeTexture( null );
  11311. } else {
  11312. node = uniform( null, uniformType );
  11313. }
  11314. if ( this.group !== null ) {
  11315. node.setGroup( this.group );
  11316. }
  11317. if ( this.name !== null ) node.setName( this.name );
  11318. this.node = node;
  11319. }
  11320. /**
  11321. * This method is overwritten since the node type is inferred from
  11322. * the type of the reference node.
  11323. *
  11324. * @param {NodeBuilder} builder - The current node builder.
  11325. * @return {string} The node type.
  11326. */
  11327. generateNodeType( builder ) {
  11328. if ( this.node === null ) {
  11329. this.updateReference( builder );
  11330. this.updateValue();
  11331. }
  11332. return this.node.getNodeType( builder );
  11333. }
  11334. /**
  11335. * Returns the property value from the given referred object.
  11336. *
  11337. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  11338. * @return {any} The value.
  11339. */
  11340. getValueFromReference( object = this.reference ) {
  11341. const { properties } = this;
  11342. let value = object[ properties[ 0 ] ];
  11343. for ( let i = 1; i < properties.length; i ++ ) {
  11344. value = value[ properties[ i ] ];
  11345. }
  11346. return value;
  11347. }
  11348. /**
  11349. * Allows to update the reference based on the given state. The state is only
  11350. * evaluated {@link ReferenceNode#object} is not set.
  11351. *
  11352. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  11353. * @return {Object} The updated reference.
  11354. */
  11355. updateReference( state ) {
  11356. this.reference = this.object !== null ? this.object : state.object;
  11357. return this.reference;
  11358. }
  11359. /**
  11360. * The output of the reference node is the internal uniform node.
  11361. *
  11362. * @param {NodeBuilder} builder - The current node builder.
  11363. * @return {UniformNode} The output node.
  11364. */
  11365. setup( /* builder */ ) {
  11366. this.updateValue();
  11367. return this.node;
  11368. }
  11369. /**
  11370. * Overwritten to update the internal uniform value.
  11371. *
  11372. * @param {NodeFrame} frame - A reference to the current node frame.
  11373. */
  11374. update( /*frame*/ ) {
  11375. this.updateValue();
  11376. }
  11377. /**
  11378. * Retrieves the value from the referred object property and uses it
  11379. * to updated the internal uniform.
  11380. */
  11381. updateValue() {
  11382. if ( this.node === null ) this.setNodeType( this.uniformType );
  11383. const value = this.getValueFromReference();
  11384. if ( Array.isArray( value ) ) {
  11385. this.node.array = value;
  11386. } else {
  11387. this.node.value = value;
  11388. }
  11389. }
  11390. }
  11391. /**
  11392. * TSL function for creating a reference node.
  11393. *
  11394. * @tsl
  11395. * @function
  11396. * @param {string} name - The name of the property the node refers to.
  11397. * @param {string} type - The uniform type that should be used to represent the property value.
  11398. * @param {?Object} [object] - The object the property belongs to.
  11399. * @returns {ReferenceNode}
  11400. */
  11401. const reference = ( name, type, object ) => new ReferenceNode( name, type, object );
  11402. /**
  11403. * TSL function for creating a reference node. Use this function if you want need a reference
  11404. * to an array-like property that should be represented as a uniform buffer.
  11405. *
  11406. * @tsl
  11407. * @function
  11408. * @param {string} name - The name of the property the node refers to.
  11409. * @param {string} type - The uniform type that should be used to represent the property value.
  11410. * @param {number} count - The number of value inside the array-like object.
  11411. * @param {Object} object - An array-like object the property belongs to.
  11412. * @returns {ReferenceNode}
  11413. */
  11414. const referenceBuffer = ( name, type, count, object ) => new ReferenceNode( name, type, object, count );
  11415. /**
  11416. * This node is a special type of reference node which is intended
  11417. * for linking material properties with node values.
  11418. * ```js
  11419. * const opacityNode = materialReference( 'opacity', 'float', material );
  11420. * ```
  11421. * When changing `material.opacity`, the node value of `opacityNode` will
  11422. * automatically be updated.
  11423. *
  11424. * @augments ReferenceNode
  11425. */
  11426. class MaterialReferenceNode extends ReferenceNode {
  11427. static get type() {
  11428. return 'MaterialReferenceNode';
  11429. }
  11430. /**
  11431. * Constructs a new material reference node.
  11432. *
  11433. * @param {string} property - The name of the property the node refers to.
  11434. * @param {string} inputType - The uniform type that should be used to represent the property value.
  11435. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  11436. * the node refers to the material of the current rendered object.
  11437. */
  11438. constructor( property, inputType, material = null ) {
  11439. super( property, inputType, material );
  11440. /**
  11441. * The material the property belongs to. When no material is set,
  11442. * the node refers to the material of the current rendered object.
  11443. *
  11444. * @type {?Material}
  11445. * @default null
  11446. */
  11447. this.material = material;
  11448. /**
  11449. * This flag can be used for type testing.
  11450. *
  11451. * @type {boolean}
  11452. * @readonly
  11453. * @default true
  11454. */
  11455. this.isMaterialReferenceNode = true;
  11456. }
  11457. /**
  11458. * Updates the reference based on the given state. The state is only evaluated
  11459. * {@link MaterialReferenceNode#material} is not set.
  11460. *
  11461. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  11462. * @return {Object} The updated reference.
  11463. */
  11464. updateReference( state ) {
  11465. this.reference = this.material !== null ? this.material : state.material;
  11466. return this.reference;
  11467. }
  11468. }
  11469. /**
  11470. * TSL function for creating a material reference node.
  11471. *
  11472. * @tsl
  11473. * @function
  11474. * @param {string} name - The name of the property the node refers to.
  11475. * @param {string} type - The uniform type that should be used to represent the property value.
  11476. * @param {?Material} [material=null] - The material the property belongs to.
  11477. * When no material is set, the node refers to the material of the current rendered object.
  11478. * @returns {MaterialReferenceNode}
  11479. */
  11480. const materialReference = ( name, type, material = null ) => new MaterialReferenceNode( name, type, material );
  11481. // Normal Mapping Without Precomputed Tangents
  11482. // http://www.thetenthplanet.de/archives/1180
  11483. const uv = uv$1();
  11484. const q0 = positionView.dFdx();
  11485. const q1 = positionView.dFdy();
  11486. const st0 = uv.dFdx();
  11487. const st1 = uv.dFdy();
  11488. const N = normalView;
  11489. const q1perp = q1.cross( N );
  11490. const q0perp = N.cross( q0 );
  11491. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  11492. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  11493. const det = T.dot( T ).max( B.dot( B ) );
  11494. const scale$1 = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  11495. /**
  11496. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  11497. * Useful for normal mapping without precomputed tangents.
  11498. *
  11499. * Reference: http://www.thetenthplanet.de/archives/1180
  11500. *
  11501. * @tsl
  11502. * @type {Node<vec3>}
  11503. */
  11504. const tangentViewFrame = /*@__PURE__*/ T.mul( scale$1 ).toVar( 'tangentViewFrame' );
  11505. /**
  11506. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  11507. * Complements the tangentViewFrame for constructing the tangent space basis.
  11508. *
  11509. * Reference: http://www.thetenthplanet.de/archives/1180
  11510. *
  11511. * @tsl
  11512. * @type {Node<vec3>}
  11513. */
  11514. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale$1 ).toVar( 'bitangentViewFrame' );
  11515. /**
  11516. * TSL object that represents the tangent attribute of the current rendered object.
  11517. *
  11518. * @tsl
  11519. * @type {Node<vec4>}
  11520. */
  11521. const tangentGeometry = /*@__PURE__*/ attribute( 'tangent', 'vec4' );
  11522. /**
  11523. * TSL object that represents the vertex tangent in local space of the current rendered object.
  11524. *
  11525. * @tsl
  11526. * @type {Node<vec3>}
  11527. */
  11528. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  11529. /**
  11530. * TSL object that represents the vertex tangent in view space of the current rendered object.
  11531. *
  11532. * @tsl
  11533. * @type {Node<vec3>}
  11534. */
  11535. const tangentView = /*@__PURE__*/ ( Fn( ( builder ) => {
  11536. let node;
  11537. if ( builder.subBuildFn === 'VERTEX' || builder.geometry.hasAttribute( 'tangent' ) ) {
  11538. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  11539. } else {
  11540. node = tangentViewFrame;
  11541. }
  11542. if ( builder.isFlatShading() !== true ) {
  11543. node = negateOnBackSide( node );
  11544. }
  11545. return node;
  11546. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  11547. /**
  11548. * TSL object that represents the vertex tangent in world space of the current rendered object.
  11549. *
  11550. * @tsl
  11551. * @type {Node<vec3>}
  11552. */
  11553. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraWorldMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  11554. /**
  11555. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  11556. *
  11557. * @tsl
  11558. * @private
  11559. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  11560. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  11561. * @returns {Node<vec3>} The bitangent node.
  11562. */
  11563. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], builder ) => {
  11564. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  11565. if ( builder.subBuildFn === 'NORMAL' && builder.isFlatShading() !== true ) {
  11566. bitangent = bitangent.toVarying( varyingName );
  11567. }
  11568. return bitangent;
  11569. } ).once( [ 'NORMAL' ] );
  11570. /**
  11571. * TSL object that represents the bitangent attribute of the current rendered object.
  11572. *
  11573. * @tsl
  11574. * @type {Node<vec3>}
  11575. */
  11576. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  11577. /**
  11578. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  11579. *
  11580. * @tsl
  11581. * @type {Node<vec3>}
  11582. */
  11583. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  11584. /**
  11585. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  11586. *
  11587. * @tsl
  11588. * @type {Node<vec3>}
  11589. */
  11590. const bitangentView = /*@__PURE__*/ ( Fn( ( builder ) => {
  11591. let node;
  11592. if ( builder.subBuildFn === 'VERTEX' || builder.geometry.hasAttribute( 'tangent' ) ) {
  11593. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  11594. } else {
  11595. node = bitangentViewFrame;
  11596. }
  11597. if ( builder.isFlatShading() !== true ) {
  11598. node = negateOnBackSide( node );
  11599. }
  11600. return node;
  11601. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  11602. /**
  11603. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  11604. *
  11605. * @tsl
  11606. * @type {Node<vec3>}
  11607. */
  11608. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  11609. /**
  11610. * TSL object that represents the TBN matrix in view space.
  11611. *
  11612. * @tsl
  11613. * @type {Node<mat3>}
  11614. */
  11615. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  11616. /**
  11617. * TSL object that represents the parallax direction.
  11618. *
  11619. * @tsl
  11620. * @type {Node<mat3>}
  11621. */
  11622. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  11623. /**
  11624. * TSL function for computing parallax uv coordinates.
  11625. *
  11626. * @tsl
  11627. * @function
  11628. * @param {Node<vec2>} uv - A uv node.
  11629. * @param {Node<vec2>} scale - A scale node.
  11630. * @returns {Node<vec2>} Parallax uv coordinates.
  11631. */
  11632. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  11633. /**
  11634. * TSL function for computing bent normals.
  11635. *
  11636. * @tsl
  11637. * @function
  11638. * @returns {Node<vec3>} Bent normals.
  11639. */
  11640. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  11641. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  11642. let bentNormal = anisotropyB.cross( positionViewDirection );
  11643. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  11644. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  11645. return bentNormal;
  11646. } ).once() )();
  11647. /**
  11648. * Packs a normal vector into a color value.
  11649. *
  11650. * @tsl
  11651. * @function
  11652. * @param {Node<vec3>} node - The direction to pack.
  11653. * @return {Node<vec3>} The color.
  11654. */
  11655. const packNormalToRGB = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  11656. /**
  11657. * Unpacks a color value into a normal vector.
  11658. *
  11659. * @tsl
  11660. * @function
  11661. * @param {Node<vec3>} node - The color to unpack.
  11662. * @return {Node<vec3>} The direction.
  11663. */
  11664. const unpackRGBToNormal = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  11665. /**
  11666. * Unpacks a tangent space normal, reconstructing the Z component by projecting the X,Y coordinates onto the hemisphere.
  11667. * The X,Y coordinates are expected to be in the [-1, 1] range.
  11668. *
  11669. * @tsl
  11670. * @function
  11671. * @param {Node<vec2>} xy - The X,Y coordinates of the normal.
  11672. * @return {Node<vec3>} The resulting normal.
  11673. */
  11674. const unpackNormal = ( xy ) => vec3( xy, sqrt( saturate( float( 1.0 ).sub( dot( xy, xy ) ) ) ) );
  11675. /**
  11676. * @tsl
  11677. * @function
  11678. * @deprecated since r185. Use {@link packNormalToRGB} instead.
  11679. * @param {Node<vec3>} node - The direction to pack.
  11680. * @returns {Node<vec3>}
  11681. */
  11682. const directionToColor = ( node ) => {
  11683. warnOnce( 'TSL: "directionToColor()" has been renamed to "packNormalToRGB()".' ); // @deprecated r185
  11684. return packNormalToRGB( node );
  11685. };
  11686. /**
  11687. * @tsl
  11688. * @function
  11689. * @deprecated since r185. Use {@link unpackRGBToNormal} instead.
  11690. * @param {Node<vec3>} node - The color to unpack.
  11691. * @returns {Node<vec3>}
  11692. */
  11693. const colorToDirection = ( node ) => {
  11694. warnOnce( 'TSL: "colorToDirection()" has been renamed to "unpackRGBToNormal()".' ); // @deprecated r185
  11695. return unpackRGBToNormal( node );
  11696. };
  11697. /**
  11698. * This class can be used for applying normals maps to materials.
  11699. *
  11700. * ```js
  11701. * material.normalNode = normalMap( texture( normalTex ) );
  11702. * ```
  11703. *
  11704. * @augments TempNode
  11705. */
  11706. class NormalMapNode extends TempNode {
  11707. static get type() {
  11708. return 'NormalMapNode';
  11709. }
  11710. /**
  11711. * Constructs a new normal map node.
  11712. *
  11713. * @param {Node<vec3>} node - Represents the normal map data.
  11714. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  11715. */
  11716. constructor( node, scaleNode = null ) {
  11717. super( 'vec3' );
  11718. /**
  11719. * Represents the normal map data.
  11720. *
  11721. * @type {Node<vec3>}
  11722. */
  11723. this.node = node;
  11724. /**
  11725. * Controls the intensity of the effect.
  11726. *
  11727. * @type {?Node<vec2>}
  11728. * @default null
  11729. */
  11730. this.scaleNode = scaleNode;
  11731. /**
  11732. * The normal map type.
  11733. *
  11734. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  11735. * @default TangentSpaceNormalMap
  11736. */
  11737. this.normalMapType = TangentSpaceNormalMap;
  11738. /**
  11739. * Controls how to unpack the sampled normal map values.
  11740. *
  11741. * @type {string}
  11742. * @default NoNormalPacking
  11743. */
  11744. this.unpackNormalMode = NoNormalPacking;
  11745. }
  11746. setup( builder ) {
  11747. const { normalMapType, scaleNode, unpackNormalMode } = this;
  11748. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  11749. if ( normalMapType === TangentSpaceNormalMap ) {
  11750. if ( unpackNormalMode === NormalRGPacking ) {
  11751. normalMap = unpackNormal( normalMap.xy );
  11752. } else if ( unpackNormalMode === NormalGAPacking ) {
  11753. normalMap = unpackNormal( normalMap.yw );
  11754. } else if ( unpackNormalMode !== NoNormalPacking ) {
  11755. error( `THREE.NodeMaterial: Unexpected unpack normal mode: ${ unpackNormalMode }` );
  11756. }
  11757. } else {
  11758. if ( unpackNormalMode !== NoNormalPacking ) {
  11759. error( `THREE.NodeMaterial: Normal map type '${ normalMapType }' is not compatible with unpack normal mode '${ unpackNormalMode }'` );
  11760. }
  11761. }
  11762. if ( scaleNode !== null ) {
  11763. let scale = scaleNode;
  11764. if ( builder.isFlatShading() === true ) {
  11765. scale = negateOnBackSide( scale );
  11766. }
  11767. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  11768. }
  11769. let output = null;
  11770. if ( normalMapType === ObjectSpaceNormalMap ) {
  11771. output = transformNormalToView( normalMap );
  11772. } else if ( normalMapType === TangentSpaceNormalMap ) {
  11773. output = TBNViewMatrix.mul( normalMap ).normalize();
  11774. } else {
  11775. error( `NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  11776. output = normalView; // Fallback to default normal view
  11777. }
  11778. return output;
  11779. }
  11780. }
  11781. /**
  11782. * TSL function for creating a normal map node.
  11783. *
  11784. * @tsl
  11785. * @function
  11786. * @param {Node<vec3>} node - Represents the normal map data.
  11787. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  11788. * @returns {NormalMapNode}
  11789. */
  11790. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  11791. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  11792. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  11793. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  11794. // It's used to preserve the same TextureNode instance
  11795. const sampleTexture = ( callback ) => textureNode.isolate().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  11796. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  11797. return vec2(
  11798. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  11799. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  11800. ).mul( bumpScale );
  11801. } );
  11802. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  11803. const perturbNormalArb = Fn( ( inputs ) => {
  11804. const { surf_pos, surf_norm, dHdxy } = inputs;
  11805. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  11806. const vSigmaX = surf_pos.dFdx().normalize();
  11807. const vSigmaY = surf_pos.dFdy().normalize();
  11808. const vN = surf_norm; // normalized
  11809. const R1 = vSigmaY.cross( vN );
  11810. const R2 = vN.cross( vSigmaX );
  11811. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  11812. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  11813. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  11814. } );
  11815. /**
  11816. * This class can be used for applying bump maps to materials.
  11817. *
  11818. * ```js
  11819. * material.normalNode = bumpMap( texture( bumpTex ) );
  11820. * ```
  11821. *
  11822. * @augments TempNode
  11823. */
  11824. class BumpMapNode extends TempNode {
  11825. static get type() {
  11826. return 'BumpMapNode';
  11827. }
  11828. /**
  11829. * Constructs a new bump map node.
  11830. *
  11831. * @param {Node<float>} textureNode - Represents the bump map data.
  11832. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11833. */
  11834. constructor( textureNode, scaleNode = null ) {
  11835. super( 'vec3' );
  11836. /**
  11837. * Represents the bump map data.
  11838. *
  11839. * @type {Node<float>}
  11840. */
  11841. this.textureNode = textureNode;
  11842. /**
  11843. * Controls the intensity of the bump effect.
  11844. *
  11845. * @type {?Node<float>}
  11846. * @default null
  11847. */
  11848. this.scaleNode = scaleNode;
  11849. }
  11850. setup( builder ) {
  11851. // Screen-space derivatives are unreliable on thin lines, so the bump
  11852. // effect is disabled for wireframe rendering.
  11853. if ( builder.material.wireframe === true ) return normalView;
  11854. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  11855. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  11856. return perturbNormalArb( {
  11857. surf_pos: positionView,
  11858. surf_norm: normalView,
  11859. dHdxy
  11860. } );
  11861. }
  11862. }
  11863. /**
  11864. * TSL function for creating a bump map node.
  11865. *
  11866. * @tsl
  11867. * @function
  11868. * @param {Node<float>} textureNode - Represents the bump map data.
  11869. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11870. * @returns {BumpMapNode}
  11871. */
  11872. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  11873. const _propertyCache = new Map();
  11874. /**
  11875. * This class should simplify the node access to material properties.
  11876. * It internal uses reference nodes to make sure changes to material
  11877. * properties are automatically reflected to predefined TSL objects
  11878. * like e.g. `materialColor`.
  11879. *
  11880. * @augments Node
  11881. */
  11882. class MaterialNode extends Node {
  11883. static get type() {
  11884. return 'MaterialNode';
  11885. }
  11886. /**
  11887. * Constructs a new material node.
  11888. *
  11889. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  11890. */
  11891. constructor( scope ) {
  11892. super();
  11893. /**
  11894. * The scope defines what material property is referred by the node.
  11895. *
  11896. * @type {string}
  11897. */
  11898. this.scope = scope;
  11899. }
  11900. /**
  11901. * Returns a cached reference node for the given property and type.
  11902. *
  11903. * @param {string} property - The name of the material property.
  11904. * @param {string} type - The uniform type of the property.
  11905. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11906. */
  11907. getCache( property, type ) {
  11908. let node = _propertyCache.get( property );
  11909. if ( node === undefined ) {
  11910. node = materialReference( property, type );
  11911. _propertyCache.set( property, node );
  11912. }
  11913. return node;
  11914. }
  11915. /**
  11916. * Returns a float-typed material reference node for the given property name.
  11917. *
  11918. * @param {string} property - The name of the material property.
  11919. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  11920. */
  11921. getFloat( property ) {
  11922. return this.getCache( property, 'float' );
  11923. }
  11924. /**
  11925. * Returns a color-typed material reference node for the given property name.
  11926. *
  11927. * @param {string} property - The name of the material property.
  11928. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  11929. */
  11930. getColor( property ) {
  11931. return this.getCache( property, 'color' );
  11932. }
  11933. /**
  11934. * Returns a texture-typed material reference node for the given property name.
  11935. *
  11936. * @param {string} property - The name of the material property.
  11937. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11938. */
  11939. getTexture( property ) {
  11940. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  11941. }
  11942. /**
  11943. * The node setup is done depending on the selected scope. Multiple material properties
  11944. * might be grouped into a single node composition if they logically belong together.
  11945. *
  11946. * @param {NodeBuilder} builder - The current node builder.
  11947. * @return {Node} The node representing the selected scope.
  11948. */
  11949. setup( builder ) {
  11950. const material = builder.context.material;
  11951. const scope = this.scope;
  11952. let node = null;
  11953. if ( scope === MaterialNode.COLOR ) {
  11954. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  11955. if ( material.map && material.map.isTexture === true ) {
  11956. node = colorNode.mul( this.getTexture( 'map' ) );
  11957. } else {
  11958. node = colorNode;
  11959. }
  11960. } else if ( scope === MaterialNode.OPACITY ) {
  11961. const opacityNode = this.getFloat( scope );
  11962. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  11963. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  11964. } else {
  11965. node = opacityNode;
  11966. }
  11967. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  11968. if ( material.specularMap && material.specularMap.isTexture === true ) {
  11969. node = this.getTexture( 'specular' ).r;
  11970. } else {
  11971. node = float( 1 );
  11972. }
  11973. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  11974. const specularIntensityNode = this.getFloat( scope );
  11975. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  11976. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  11977. } else {
  11978. node = specularIntensityNode;
  11979. }
  11980. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  11981. const specularColorNode = this.getColor( scope );
  11982. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  11983. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  11984. } else {
  11985. node = specularColorNode;
  11986. }
  11987. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  11988. const roughnessNode = this.getFloat( scope );
  11989. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  11990. node = roughnessNode.mul( this.getTexture( scope ).g );
  11991. } else {
  11992. node = roughnessNode;
  11993. }
  11994. } else if ( scope === MaterialNode.METALNESS ) {
  11995. const metalnessNode = this.getFloat( scope );
  11996. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  11997. node = metalnessNode.mul( this.getTexture( scope ).b );
  11998. } else {
  11999. node = metalnessNode;
  12000. }
  12001. } else if ( scope === MaterialNode.EMISSIVE ) {
  12002. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  12003. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  12004. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  12005. node = emissiveNode.mul( this.getTexture( scope ) );
  12006. } else {
  12007. node = emissiveNode;
  12008. }
  12009. } else if ( scope === MaterialNode.NORMAL ) {
  12010. if ( material.normalMap ) {
  12011. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  12012. node.normalMapType = material.normalMapType;
  12013. if ( material.normalMap.format == RGFormat || material.normalMap.format == RED_GREEN_RGTC2_Format || material.normalMap.format == RG11_EAC_Format ) {
  12014. node.unpackNormalMode = NormalRGPacking;
  12015. }
  12016. } else if ( material.bumpMap ) {
  12017. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  12018. } else {
  12019. node = normalView;
  12020. }
  12021. } else if ( scope === MaterialNode.CLEARCOAT ) {
  12022. const clearcoatNode = this.getFloat( scope );
  12023. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  12024. node = clearcoatNode.mul( this.getTexture( scope ).r );
  12025. } else {
  12026. node = clearcoatNode;
  12027. }
  12028. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  12029. const clearcoatRoughnessNode = this.getFloat( scope );
  12030. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  12031. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  12032. } else {
  12033. node = clearcoatRoughnessNode;
  12034. }
  12035. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  12036. if ( material.clearcoatNormalMap ) {
  12037. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  12038. } else {
  12039. node = normalView;
  12040. }
  12041. } else if ( scope === MaterialNode.SHEEN ) {
  12042. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  12043. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  12044. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  12045. } else {
  12046. node = sheenNode;
  12047. }
  12048. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  12049. const sheenRoughnessNode = this.getFloat( scope );
  12050. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  12051. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  12052. } else {
  12053. node = sheenRoughnessNode;
  12054. }
  12055. node = node.clamp( 0.0001, 1.0 );
  12056. } else if ( scope === MaterialNode.ANISOTROPY ) {
  12057. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  12058. const anisotropyPolar = this.getTexture( scope );
  12059. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  12060. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  12061. } else {
  12062. node = materialAnisotropyVector;
  12063. }
  12064. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  12065. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  12066. if ( material.iridescenceThicknessMap ) {
  12067. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  12068. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  12069. } else {
  12070. node = iridescenceThicknessMaximum;
  12071. }
  12072. } else if ( scope === MaterialNode.TRANSMISSION ) {
  12073. const transmissionNode = this.getFloat( scope );
  12074. if ( material.transmissionMap ) {
  12075. node = transmissionNode.mul( this.getTexture( scope ).r );
  12076. } else {
  12077. node = transmissionNode;
  12078. }
  12079. } else if ( scope === MaterialNode.THICKNESS ) {
  12080. const thicknessNode = this.getFloat( scope );
  12081. if ( material.thicknessMap ) {
  12082. node = thicknessNode.mul( this.getTexture( scope ).g );
  12083. } else {
  12084. node = thicknessNode;
  12085. }
  12086. } else if ( scope === MaterialNode.IOR ) {
  12087. node = this.getFloat( scope );
  12088. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  12089. if ( material.lightMap ) {
  12090. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  12091. } else {
  12092. node = vec3( 0.0 );
  12093. }
  12094. } else if ( scope === MaterialNode.AO ) {
  12095. if ( material.aoMap ) {
  12096. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  12097. } else {
  12098. node = float( 1.0 );
  12099. }
  12100. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  12101. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  12102. } else {
  12103. const outputType = this.getNodeType( builder );
  12104. node = this.getCache( scope, outputType );
  12105. }
  12106. return node;
  12107. }
  12108. }
  12109. MaterialNode.ALPHA_TEST = 'alphaTest';
  12110. MaterialNode.COLOR = 'color';
  12111. MaterialNode.OPACITY = 'opacity';
  12112. MaterialNode.SHININESS = 'shininess';
  12113. MaterialNode.SPECULAR = 'specular';
  12114. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  12115. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  12116. MaterialNode.SPECULAR_COLOR = 'specularColor';
  12117. MaterialNode.REFLECTIVITY = 'reflectivity';
  12118. MaterialNode.ROUGHNESS = 'roughness';
  12119. MaterialNode.METALNESS = 'metalness';
  12120. MaterialNode.NORMAL = 'normal';
  12121. MaterialNode.CLEARCOAT = 'clearcoat';
  12122. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  12123. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  12124. MaterialNode.EMISSIVE = 'emissive';
  12125. MaterialNode.ROTATION = 'rotation';
  12126. MaterialNode.SHEEN = 'sheen';
  12127. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  12128. MaterialNode.ANISOTROPY = 'anisotropy';
  12129. MaterialNode.IRIDESCENCE = 'iridescence';
  12130. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  12131. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  12132. MaterialNode.IOR = 'ior';
  12133. MaterialNode.TRANSMISSION = 'transmission';
  12134. MaterialNode.THICKNESS = 'thickness';
  12135. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  12136. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  12137. MaterialNode.LINE_SCALE = 'scale';
  12138. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  12139. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  12140. MaterialNode.LINE_WIDTH = 'linewidth';
  12141. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  12142. MaterialNode.POINT_SIZE = 'size';
  12143. MaterialNode.DISPERSION = 'dispersion';
  12144. MaterialNode.LIGHT_MAP = 'light';
  12145. MaterialNode.AO = 'ao';
  12146. /**
  12147. * TSL object that represents alpha test of the current material.
  12148. *
  12149. * @tsl
  12150. * @type {Node<float>}
  12151. */
  12152. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  12153. /**
  12154. * TSL object that represents the diffuse color of the current material.
  12155. * The value is composed via `color` * `map`.
  12156. *
  12157. * @tsl
  12158. * @type {Node<vec3>}
  12159. */
  12160. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  12161. /**
  12162. * TSL object that represents the shininess of the current material.
  12163. *
  12164. * @tsl
  12165. * @type {Node<float>}
  12166. */
  12167. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  12168. /**
  12169. * TSL object that represents the emissive color of the current material.
  12170. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  12171. *
  12172. * @tsl
  12173. * @type {Node<vec3>}
  12174. */
  12175. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  12176. /**
  12177. * TSL object that represents the opacity of the current material.
  12178. * The value is composed via `opacity` * `alphaMap`.
  12179. *
  12180. * @tsl
  12181. * @type {Node<float>}
  12182. */
  12183. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  12184. /**
  12185. * TSL object that represents the specular of the current material.
  12186. *
  12187. * @tsl
  12188. * @type {Node<vec3>}
  12189. */
  12190. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  12191. /**
  12192. * TSL object that represents the specular intensity of the current material.
  12193. * The value is composed via `specularIntensity` * `specularMap.a`.
  12194. *
  12195. * @tsl
  12196. * @type {Node<float>}
  12197. */
  12198. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  12199. /**
  12200. * TSL object that represents the specular color of the current material.
  12201. * The value is composed via `specularColor` * `specularMap.rgb`.
  12202. *
  12203. * @tsl
  12204. * @type {Node<vec3>}
  12205. */
  12206. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  12207. /**
  12208. * TSL object that represents the specular strength of the current material.
  12209. * The value is composed via `specularMap.r`.
  12210. *
  12211. * @tsl
  12212. * @type {Node<float>}
  12213. */
  12214. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  12215. /**
  12216. * TSL object that represents the reflectivity of the current material.
  12217. *
  12218. * @tsl
  12219. * @type {Node<float>}
  12220. */
  12221. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  12222. /**
  12223. * TSL object that represents the roughness of the current material.
  12224. * The value is composed via `roughness` * `roughnessMap.g`.
  12225. *
  12226. * @tsl
  12227. * @type {Node<float>}
  12228. */
  12229. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  12230. /**
  12231. * TSL object that represents the metalness of the current material.
  12232. * The value is composed via `metalness` * `metalnessMap.b`.
  12233. *
  12234. * @tsl
  12235. * @type {Node<float>}
  12236. */
  12237. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  12238. /**
  12239. * TSL object that represents the normal of the current material.
  12240. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  12241. *
  12242. * @tsl
  12243. * @type {Node<vec3>}
  12244. */
  12245. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  12246. /**
  12247. * TSL object that represents the clearcoat of the current material.
  12248. * The value is composed via `clearcoat` * `clearcoatMap.r`
  12249. *
  12250. * @tsl
  12251. * @type {Node<float>}
  12252. */
  12253. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  12254. /**
  12255. * TSL object that represents the clearcoat roughness of the current material.
  12256. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  12257. *
  12258. * @tsl
  12259. * @type {Node<float>}
  12260. */
  12261. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  12262. /**
  12263. * TSL object that represents the clearcoat normal of the current material.
  12264. * The value will be either `clearcoatNormalMap` or `normalView`.
  12265. *
  12266. * @tsl
  12267. * @type {Node<vec3>}
  12268. */
  12269. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  12270. /**
  12271. * TSL object that represents the rotation of the current sprite material.
  12272. *
  12273. * @tsl
  12274. * @type {Node<float>}
  12275. */
  12276. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  12277. /**
  12278. * TSL object that represents the sheen color of the current material.
  12279. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  12280. *
  12281. * @tsl
  12282. * @type {Node<vec3>}
  12283. */
  12284. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  12285. /**
  12286. * TSL object that represents the sheen roughness of the current material.
  12287. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  12288. *
  12289. * @tsl
  12290. * @type {Node<float>}
  12291. */
  12292. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  12293. /**
  12294. * TSL object that represents the anisotropy of the current material.
  12295. *
  12296. * @tsl
  12297. * @type {Node<vec2>}
  12298. */
  12299. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  12300. /**
  12301. * TSL object that represents the iridescence of the current material.
  12302. *
  12303. * @tsl
  12304. * @type {Node<float>}
  12305. */
  12306. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  12307. /**
  12308. * TSL object that represents the iridescence IOR of the current material.
  12309. *
  12310. * @tsl
  12311. * @type {Node<float>}
  12312. */
  12313. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  12314. /**
  12315. * TSL object that represents the iridescence thickness of the current material.
  12316. *
  12317. * @tsl
  12318. * @type {Node<float>}
  12319. */
  12320. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  12321. /**
  12322. * TSL object that represents the transmission of the current material.
  12323. * The value is composed via `transmission` * `transmissionMap.r`.
  12324. *
  12325. * @tsl
  12326. * @type {Node<float>}
  12327. */
  12328. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  12329. /**
  12330. * TSL object that represents the thickness of the current material.
  12331. * The value is composed via `thickness` * `thicknessMap.g`.
  12332. *
  12333. * @tsl
  12334. * @type {Node<float>}
  12335. */
  12336. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  12337. /**
  12338. * TSL object that represents the IOR of the current material.
  12339. *
  12340. * @tsl
  12341. * @type {Node<float>}
  12342. */
  12343. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  12344. /**
  12345. * TSL object that represents the attenuation distance of the current material.
  12346. *
  12347. * @tsl
  12348. * @type {Node<float>}
  12349. */
  12350. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  12351. /**
  12352. * TSL object that represents the attenuation color of the current material.
  12353. *
  12354. * @tsl
  12355. * @type {Node<vec3>}
  12356. */
  12357. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  12358. /**
  12359. * TSL object that represents the scale of the current dashed line material.
  12360. *
  12361. * @tsl
  12362. * @type {Node<float>}
  12363. */
  12364. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  12365. /**
  12366. * TSL object that represents the dash size of the current dashed line material.
  12367. *
  12368. * @tsl
  12369. * @type {Node<float>}
  12370. */
  12371. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  12372. /**
  12373. * TSL object that represents the gap size of the current dashed line material.
  12374. *
  12375. * @tsl
  12376. * @type {Node<float>}
  12377. */
  12378. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  12379. /**
  12380. * TSL object that represents the line width of the current line material.
  12381. *
  12382. * @tsl
  12383. * @type {Node<float>}
  12384. */
  12385. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  12386. /**
  12387. * TSL object that represents the dash offset of the current line material.
  12388. *
  12389. * @tsl
  12390. * @type {Node<float>}
  12391. */
  12392. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  12393. /**
  12394. * TSL object that represents the point size of the current points material.
  12395. *
  12396. * @tsl
  12397. * @type {Node<float>}
  12398. */
  12399. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  12400. /**
  12401. * TSL object that represents the dispersion of the current material.
  12402. *
  12403. * @tsl
  12404. * @type {Node<float>}
  12405. */
  12406. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  12407. /**
  12408. * TSL object that represents the light map of the current material.
  12409. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  12410. *
  12411. * @tsl
  12412. * @type {Node<vec3>}
  12413. */
  12414. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  12415. /**
  12416. * TSL object that represents the ambient occlusion map of the current material.
  12417. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  12418. *
  12419. * @tsl
  12420. * @type {Node<float>}
  12421. */
  12422. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  12423. /**
  12424. * TSL object that represents the anisotropy vector of the current material.
  12425. *
  12426. * @tsl
  12427. * @type {Node<vec2>}
  12428. */
  12429. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  12430. return frame.material;
  12431. } ).onRenderUpdate( function ( { material } ) {
  12432. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  12433. } );
  12434. /**
  12435. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  12436. *
  12437. * @tsl
  12438. * @type {VaryingNode<vec4>}
  12439. */
  12440. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  12441. return builder.context.setupModelViewProjection();
  12442. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  12443. /**
  12444. * EventNode is a node that executes a callback during specific update phases.
  12445. *
  12446. * @augments Node
  12447. */
  12448. class EventNode extends Node {
  12449. static get type() {
  12450. return 'EventNode';
  12451. }
  12452. /**
  12453. * Creates an EventNode.
  12454. *
  12455. * @param {string} eventType - The type of event
  12456. * @param {Function} callback - The callback to execute on update.
  12457. */
  12458. constructor( eventType, callback ) {
  12459. super( 'void' );
  12460. this.eventType = eventType;
  12461. this.callback = callback;
  12462. if ( eventType === EventNode.OBJECT ) {
  12463. this.updateType = NodeUpdateType.OBJECT;
  12464. } else if ( eventType === EventNode.MATERIAL ) {
  12465. this.updateType = NodeUpdateType.RENDER;
  12466. } else if ( eventType === EventNode.FRAME ) {
  12467. this.updateType = NodeUpdateType.FRAME;
  12468. } else if ( eventType === EventNode.BEFORE_OBJECT ) {
  12469. this.updateBeforeType = NodeUpdateType.OBJECT;
  12470. } else if ( eventType === EventNode.BEFORE_MATERIAL ) {
  12471. this.updateBeforeType = NodeUpdateType.RENDER;
  12472. } else if ( eventType === EventNode.BEFORE_FRAME ) {
  12473. this.updateBeforeType = NodeUpdateType.FRAME;
  12474. }
  12475. }
  12476. update( frame ) {
  12477. this.callback( frame );
  12478. }
  12479. updateBefore( frame ) {
  12480. this.callback( frame );
  12481. }
  12482. }
  12483. EventNode.OBJECT = 'object';
  12484. EventNode.MATERIAL = 'material';
  12485. EventNode.FRAME = 'frame';
  12486. EventNode.BEFORE_OBJECT = 'beforeObject';
  12487. EventNode.BEFORE_MATERIAL = 'beforeMaterial';
  12488. EventNode.BEFORE_FRAME = 'beforeFrame';
  12489. /**
  12490. * Helper to create an EventNode and add it to the stack.
  12491. *
  12492. * @param {string} type - The event type.
  12493. * @param {Function} callback - The callback function.
  12494. * @returns {EventNode}
  12495. */
  12496. const createEvent = ( type, callback ) => new EventNode( type, callback ).toStack();
  12497. /**
  12498. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  12499. *
  12500. * 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.
  12501. *
  12502. * @param {Function} callback - The callback function.
  12503. * @returns {EventNode}
  12504. */
  12505. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  12506. /**
  12507. * Creates an event that triggers a function when the first object that uses the material is rendered.
  12508. *
  12509. * 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.
  12510. *
  12511. * @param {Function} callback - The callback function.
  12512. * @returns {EventNode}
  12513. */
  12514. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  12515. /**
  12516. * Creates an event that triggers a function every frame.
  12517. *
  12518. * 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.
  12519. *
  12520. * @param {Function} callback - The callback function.
  12521. * @returns {EventNode}
  12522. */
  12523. const OnFrameUpdate = ( callback ) => createEvent( EventNode.FRAME, callback );
  12524. /**
  12525. * Creates an event that triggers a function before an object (Mesh|Sprite) is updated.
  12526. *
  12527. * 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.
  12528. *
  12529. * @param {Function} callback - The callback function.
  12530. * @returns {EventNode}
  12531. */
  12532. const OnBeforeObjectUpdate = ( callback ) => createEvent( EventNode.BEFORE_OBJECT, callback );
  12533. /**
  12534. * Creates an event that triggers a function before the material is updated.
  12535. *
  12536. * 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.
  12537. *
  12538. * @param {Function} callback - The callback function.
  12539. * @returns {EventNode}
  12540. */
  12541. const OnBeforeMaterialUpdate = ( callback ) => createEvent( EventNode.BEFORE_MATERIAL, callback );
  12542. /**
  12543. * Creates an event that triggers a function before every frame.
  12544. *
  12545. * 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.
  12546. *
  12547. * @param {Function} callback - The callback function.
  12548. * @returns {EventNode}
  12549. */
  12550. const OnBeforeFrameUpdate = ( callback ) => createEvent( EventNode.BEFORE_FRAME, callback );
  12551. /**
  12552. * This class enables element access on instances of {@link StorageBufferNode}.
  12553. * In most cases, it is indirectly used when accessing elements with the
  12554. * {@link StorageBufferNode#element} method.
  12555. *
  12556. * ```js
  12557. * const position = positionStorage.element( instanceIndex );
  12558. * ```
  12559. *
  12560. * @augments ArrayElementNode
  12561. */
  12562. class StorageArrayElementNode extends ArrayElementNode {
  12563. static get type() {
  12564. return 'StorageArrayElementNode';
  12565. }
  12566. /**
  12567. * Constructs storage buffer element node.
  12568. *
  12569. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  12570. * @param {Node} indexNode - The index node that defines the element access.
  12571. */
  12572. constructor( storageBufferNode, indexNode ) {
  12573. super( storageBufferNode, indexNode );
  12574. /**
  12575. * This flag can be used for type testing.
  12576. *
  12577. * @type {boolean}
  12578. * @readonly
  12579. * @default true
  12580. */
  12581. this.isStorageArrayElementNode = true;
  12582. }
  12583. /**
  12584. * The storage buffer node.
  12585. *
  12586. * @param {Node} value
  12587. * @type {StorageBufferNode}
  12588. */
  12589. set storageBufferNode( value ) {
  12590. this.node = value;
  12591. }
  12592. get storageBufferNode() {
  12593. return this.node;
  12594. }
  12595. getMemberType( builder, name ) {
  12596. const structTypeNode = this.storageBufferNode.structTypeNode;
  12597. if ( structTypeNode ) {
  12598. return structTypeNode.getMemberType( builder, name );
  12599. }
  12600. return 'void';
  12601. }
  12602. setup( builder ) {
  12603. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  12604. if ( this.node.isPBO === true ) {
  12605. builder.setupPBO( this.node );
  12606. }
  12607. }
  12608. return super.setup( builder );
  12609. }
  12610. generate( builder, output ) {
  12611. let snippet;
  12612. const isAssignContext = builder.isContextAssign();
  12613. //
  12614. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  12615. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  12616. snippet = builder.generatePBO( this );
  12617. } else {
  12618. snippet = this.node.build( builder );
  12619. }
  12620. } else {
  12621. snippet = super.generate( builder );
  12622. }
  12623. if ( isAssignContext !== true ) {
  12624. const type = this.getNodeType( builder );
  12625. snippet = builder.format( snippet, type, output );
  12626. }
  12627. return snippet;
  12628. }
  12629. }
  12630. /**
  12631. * TSL function for creating a storage element node.
  12632. *
  12633. * @tsl
  12634. * @function
  12635. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  12636. * @param {Node} indexNode - The index node that defines the element access.
  12637. * @returns {StorageArrayElementNode}
  12638. */
  12639. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  12640. /**
  12641. * This node is used in context of compute shaders and allows to define a
  12642. * storage buffer for data. A typical workflow is to create instances of
  12643. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  12644. * setup up a compute shader that writes into the buffers and then convert
  12645. * the storage buffers to attribute nodes for rendering.
  12646. *
  12647. * ```js
  12648. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  12649. *
  12650. * const computeInit = Fn( () => { // the compute shader
  12651. *
  12652. * const position = positionBuffer.element( instanceIndex );
  12653. *
  12654. * // compute position data
  12655. *
  12656. * position.x = 1;
  12657. * position.y = 1;
  12658. * position.z = 1;
  12659. *
  12660. * } )().compute( particleCount );
  12661. *
  12662. * const particleMaterial = new THREE.SpriteNodeMaterial();
  12663. * particleMaterial.positionNode = positionBuffer.toAttribute();
  12664. *
  12665. * renderer.computeAsync( computeInit );
  12666. *
  12667. * ```
  12668. *
  12669. * @augments BufferNode
  12670. */
  12671. class StorageBufferNode extends BufferNode {
  12672. static get type() {
  12673. return 'StorageBufferNode';
  12674. }
  12675. /**
  12676. * Constructs a new storage buffer node.
  12677. *
  12678. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12679. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  12680. * @param {number} [bufferCount=0] - The buffer count.
  12681. */
  12682. constructor( value, bufferType = null, bufferCount = 0 ) {
  12683. let nodeType, structTypeNode = null;
  12684. if ( bufferType && bufferType.isStructTypeNode ) {
  12685. nodeType = 'struct';
  12686. structTypeNode = bufferType;
  12687. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  12688. bufferCount = value.count;
  12689. }
  12690. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  12691. nodeType = getTypeFromLength( value.itemSize );
  12692. bufferCount = value.count;
  12693. } else {
  12694. nodeType = bufferType;
  12695. }
  12696. super( value, nodeType, bufferCount );
  12697. /**
  12698. * This flag can be used for type testing.
  12699. *
  12700. * @type {boolean}
  12701. * @readonly
  12702. * @default true
  12703. */
  12704. this.isStorageBufferNode = true;
  12705. /**
  12706. * The buffer struct type.
  12707. *
  12708. * @type {?StructTypeNode}
  12709. * @default null
  12710. */
  12711. this.structTypeNode = structTypeNode;
  12712. /**
  12713. * The access type of the texture node.
  12714. *
  12715. * @type {string}
  12716. * @default 'readWrite'
  12717. */
  12718. this.access = NodeAccess.READ_WRITE;
  12719. /**
  12720. * Whether the node is atomic or not.
  12721. *
  12722. * @type {boolean}
  12723. * @default false
  12724. */
  12725. this.isAtomic = false;
  12726. /**
  12727. * Whether the node represents a PBO or not.
  12728. * Only relevant for WebGL.
  12729. *
  12730. * @type {boolean}
  12731. * @default false
  12732. */
  12733. this.isPBO = false;
  12734. /**
  12735. * A reference to the internal buffer attribute node.
  12736. *
  12737. * @private
  12738. * @type {?BufferAttributeNode}
  12739. * @default null
  12740. */
  12741. this._attribute = null;
  12742. /**
  12743. * A reference to the internal varying node.
  12744. *
  12745. * @private
  12746. * @type {?VaryingNode}
  12747. * @default null
  12748. */
  12749. this._varying = null;
  12750. /**
  12751. * `StorageBufferNode` sets this property to `true` by default.
  12752. *
  12753. * @type {boolean}
  12754. * @default true
  12755. */
  12756. this.global = true;
  12757. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  12758. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  12759. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  12760. else value.isStorageBufferAttribute = true;
  12761. }
  12762. }
  12763. /**
  12764. * This method is overwritten since the buffer data might be shared
  12765. * and thus the hash should be shared as well.
  12766. *
  12767. * @param {NodeBuilder} builder - The current node builder.
  12768. * @return {string} The hash.
  12769. */
  12770. getHash( builder ) {
  12771. let id;
  12772. if ( this.bufferCount === 0 ) {
  12773. let bufferData = builder.globalCache.getData( this.value );
  12774. if ( bufferData === undefined ) {
  12775. bufferData = {
  12776. node: this
  12777. };
  12778. builder.globalCache.setData( this.value, bufferData );
  12779. }
  12780. id = bufferData.node.id;
  12781. } else {
  12782. id = this.id;
  12783. }
  12784. return String( id );
  12785. }
  12786. /**
  12787. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  12788. *
  12789. * @param {NodeBuilder} builder - The current node builder.
  12790. * @return {string} The input type.
  12791. */
  12792. getInputType( /*builder*/ ) {
  12793. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  12794. }
  12795. /**
  12796. * Enables element access with the given index node.
  12797. *
  12798. * @param {IndexNode} indexNode - The index node.
  12799. * @return {StorageArrayElementNode} A node representing the element access.
  12800. */
  12801. element( indexNode ) {
  12802. return storageElement( this, indexNode );
  12803. }
  12804. /**
  12805. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  12806. *
  12807. * @param {boolean} value - The value so set.
  12808. * @return {StorageBufferNode} A reference to this node.
  12809. */
  12810. setPBO( value ) {
  12811. this.isPBO = value;
  12812. return this;
  12813. }
  12814. /**
  12815. * Returns the `isPBO` value.
  12816. *
  12817. * @return {boolean} Whether the node represents a PBO or not.
  12818. */
  12819. getPBO() {
  12820. return this.isPBO;
  12821. }
  12822. /**
  12823. * Defines the node access.
  12824. *
  12825. * @param {string} value - The node access.
  12826. * @return {StorageBufferNode} A reference to this node.
  12827. */
  12828. setAccess( value ) {
  12829. this.access = value;
  12830. return this;
  12831. }
  12832. /**
  12833. * Convenience method for configuring a read-only node access.
  12834. *
  12835. * @return {StorageBufferNode} A reference to this node.
  12836. */
  12837. toReadOnly() {
  12838. return this.setAccess( NodeAccess.READ_ONLY );
  12839. }
  12840. /**
  12841. * Defines whether the node is atomic or not.
  12842. *
  12843. * @param {boolean} value - The atomic flag.
  12844. * @return {StorageBufferNode} A reference to this node.
  12845. */
  12846. setAtomic( value ) {
  12847. this.isAtomic = value;
  12848. return this;
  12849. }
  12850. /**
  12851. * Convenience method for making this node atomic.
  12852. *
  12853. * @return {StorageBufferNode} A reference to this node.
  12854. */
  12855. toAtomic() {
  12856. return this.setAtomic( true );
  12857. }
  12858. /**
  12859. * Returns attribute data for this storage buffer node.
  12860. *
  12861. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  12862. */
  12863. getAttributeData() {
  12864. if ( this._attribute === null ) {
  12865. this._attribute = bufferAttribute( this.value );
  12866. this._varying = varying( this._attribute );
  12867. }
  12868. return {
  12869. attribute: this._attribute,
  12870. varying: this._varying
  12871. };
  12872. }
  12873. /**
  12874. * This method is overwritten since the node type from the availability of storage buffers
  12875. * and the attribute data.
  12876. *
  12877. * @param {NodeBuilder} builder - The current node builder.
  12878. * @return {string} The node type.
  12879. */
  12880. generateNodeType( builder ) {
  12881. if ( this.structTypeNode !== null ) {
  12882. return this.structTypeNode.getNodeType( builder );
  12883. }
  12884. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12885. return super.generateNodeType( builder );
  12886. }
  12887. const { attribute } = this.getAttributeData();
  12888. return attribute.getNodeType( builder );
  12889. }
  12890. /**
  12891. * Returns the type of a member of the struct.
  12892. *
  12893. * @param {NodeBuilder} builder - The current node builder.
  12894. * @param {string} name - The name of the member.
  12895. * @return {string} The type of the member.
  12896. */
  12897. getMemberType( builder, name ) {
  12898. if ( this.structTypeNode !== null ) {
  12899. return this.structTypeNode.getMemberType( builder, name );
  12900. }
  12901. return 'void';
  12902. }
  12903. /**
  12904. * Generates the code snippet of the storage buffer node.
  12905. *
  12906. * @param {NodeBuilder} builder - The current node builder.
  12907. * @return {string} The generated code snippet.
  12908. */
  12909. generate( builder ) {
  12910. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  12911. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12912. return super.generate( builder );
  12913. }
  12914. const { attribute, varying } = this.getAttributeData();
  12915. const output = varying.build( builder );
  12916. builder.registerTransform( output, attribute );
  12917. return output;
  12918. }
  12919. }
  12920. /**
  12921. * TSL function for creating a storage buffer node.
  12922. *
  12923. * @tsl
  12924. * @function
  12925. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12926. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  12927. * @param {number} [count=0] - The buffer count.
  12928. * @returns {StorageBufferNode}
  12929. */
  12930. const storage = ( value, type = null, count = 0 ) => new StorageBufferNode( value, type, count );
  12931. const _matrixBuffers = /*@__PURE__*/ new WeakMap();
  12932. const _colorBuffers = /*@__PURE__*/ new WeakMap();
  12933. const _previousInstanceMatrices = /*@__PURE__*/ new WeakMap();
  12934. /**
  12935. * Creates the appropriate node for instanced matrix transformations.
  12936. * Depending on buffer limits and storage capability, returns either a storage, buffer, or instanced interleaved attribute node.
  12937. *
  12938. * @param {NodeBuilder} builder - The current node builder.
  12939. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - The matrix buffer attribute.
  12940. * @param {number} count - The instance count.
  12941. * @returns {Node} The matrix node.
  12942. */
  12943. function createInstanceMatrixNode( builder, instanceMatrix, count ) {
  12944. let instanceMatrixNode;
  12945. const isStorageMatrix = instanceMatrix.isStorageInstancedBufferAttribute === true;
  12946. if ( isStorageMatrix ) {
  12947. instanceMatrixNode = storage( instanceMatrix, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12948. } else {
  12949. const uniformBufferSize = count * 16 * 4;
  12950. if ( uniformBufferSize <= builder.getUniformBufferLimit() ) {
  12951. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12952. } else {
  12953. let interleaved = _matrixBuffers.get( instanceMatrix );
  12954. if ( ! interleaved ) {
  12955. interleaved = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  12956. _matrixBuffers.set( instanceMatrix, interleaved );
  12957. }
  12958. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  12959. const instanceBuffers = [
  12960. bufferFn( interleaved, 'vec4', 16, 0 ),
  12961. bufferFn( interleaved, 'vec4', 16, 4 ),
  12962. bufferFn( interleaved, 'vec4', 16, 8 ),
  12963. bufferFn( interleaved, 'vec4', 16, 12 )
  12964. ];
  12965. instanceMatrixNode = mat4( ...instanceBuffers );
  12966. }
  12967. }
  12968. return instanceMatrixNode;
  12969. }
  12970. /**
  12971. * Retrieves or initializes the previous frame instance matrix node for motion vectors.
  12972. * Uses a WeakMap to cache previous frame instance matrices and their TSL nodes.
  12973. *
  12974. * @param {InstancedMesh} instancedMesh - The instanced mesh object.
  12975. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - The current matrix buffer attribute.
  12976. * @param {NodeBuilder} builder - The current node builder.
  12977. * @param {number} count - The instance count.
  12978. * @returns {Node} The previous frame instance matrix node.
  12979. */
  12980. function getPreviousInstance( instancedMesh, instanceMatrix, builder, count ) {
  12981. let data = _previousInstanceMatrices.get( instancedMesh );
  12982. if ( data === undefined ) {
  12983. const previousInstanceMatrix = instanceMatrix.clone();
  12984. data = {
  12985. previousInstanceMatrix,
  12986. node: createInstanceMatrixNode( builder, previousInstanceMatrix, count )
  12987. };
  12988. _previousInstanceMatrices.set( instancedMesh, data );
  12989. }
  12990. return data.node;
  12991. }
  12992. /**
  12993. * TSL object representing a varying property for the instanced color vector.
  12994. *
  12995. * @type {VaryingNode<vec3>}
  12996. */
  12997. const instanceColor = /*@__PURE__*/ varyingProperty( 'vec3', 'vInstanceColor' );
  12998. /**
  12999. * TSL function representing the standard instancing vertex shader setup.
  13000. * Transforms positionLocal and normalLocal, and assigns varying color in-place.
  13001. *
  13002. * @tsl
  13003. * @function
  13004. * @param {number} count - The instance count.
  13005. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} matrices - The instanced transformation matrices.
  13006. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} [colors=null] - The optional instanced colors.
  13007. */
  13008. const instance = /*@__PURE__*/ Fn( ( [ count, matrices, colors = null ], builder ) => {
  13009. // get numeric value (non-node)
  13010. count = count.value;
  13011. const isStorageMatrix = matrices.isStorageInstancedBufferAttribute === true;
  13012. const isStorageColor = colors && colors.isStorageInstancedBufferAttribute === true;
  13013. const instanceMatrixNode = createInstanceMatrixNode( builder, matrices, count );
  13014. // interleaved buffer tracking for matrix
  13015. let interleavedMatrix = null;
  13016. if ( ! isStorageMatrix ) {
  13017. const uniformBufferSize = count * 16 * 4;
  13018. if ( uniformBufferSize > builder.getUniformBufferLimit() ) {
  13019. interleavedMatrix = _matrixBuffers.get( matrices );
  13020. }
  13021. }
  13022. let instanceColorNode = null;
  13023. let interleavedColor = null;
  13024. if ( colors ) {
  13025. if ( isStorageColor ) {
  13026. instanceColorNode = storage( colors, 'vec3', Math.max( colors.count, 1 ) ).element( instanceIndex );
  13027. } else {
  13028. let bufferAttribute = _colorBuffers.get( colors );
  13029. if ( ! bufferAttribute ) {
  13030. bufferAttribute = new InstancedBufferAttribute( colors.array, 3 );
  13031. _colorBuffers.set( colors, bufferAttribute );
  13032. }
  13033. interleavedColor = bufferAttribute;
  13034. const bufferFn = colors.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  13035. instanceColorNode = vec3( bufferFn( bufferAttribute, 'vec3', 3, 0 ) );
  13036. }
  13037. }
  13038. // Synchronization of dynamic buffer updates per frame
  13039. if ( interleavedMatrix !== null || interleavedColor !== null ) {
  13040. OnFrameUpdate( () => {
  13041. if ( interleavedMatrix !== null ) {
  13042. interleavedMatrix.clearUpdateRanges();
  13043. interleavedMatrix.updateRanges.push( ...matrices.updateRanges );
  13044. if ( matrices.version !== interleavedMatrix.version ) {
  13045. interleavedMatrix.version = matrices.version;
  13046. }
  13047. }
  13048. if ( colors && interleavedColor !== null ) {
  13049. interleavedColor.clearUpdateRanges();
  13050. interleavedColor.updateRanges.push( ...colors.updateRanges );
  13051. if ( colors.version !== interleavedColor.version ) {
  13052. interleavedColor.version = colors.version;
  13053. }
  13054. }
  13055. } );
  13056. }
  13057. // POSITION
  13058. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  13059. positionLocal.assign( instancePosition );
  13060. if ( builder.needsPreviousData() ) {
  13061. const instancedMesh = builder.object;
  13062. OnObjectUpdate( ( { object } ) => {
  13063. const previousInstanceData = _previousInstanceMatrices.get( object );
  13064. previousInstanceData.previousInstanceMatrix.array.set( matrices.array );
  13065. } );
  13066. const previousInstanceMatrixNode = getPreviousInstance( instancedMesh, matrices, builder, count );
  13067. positionPrevious.assign( previousInstanceMatrixNode.mul( positionPrevious ).xyz );
  13068. }
  13069. // NORMAL
  13070. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  13071. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  13072. normalLocal.assign( instanceNormal );
  13073. }
  13074. // COLOR
  13075. if ( instanceColorNode !== null ) {
  13076. instanceColor.assign( instanceColorNode );
  13077. }
  13078. }, 'void' );
  13079. /**
  13080. * TSL wrapper for applying instanced mesh rendering setup.
  13081. *
  13082. * @tsl
  13083. * @function
  13084. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  13085. */
  13086. const instancedMesh = /*@__PURE__*/ Fn( ( [ instancedMesh ] ) => {
  13087. const { count, instanceMatrix, instanceColor } = instancedMesh;
  13088. instance( count, instanceMatrix, instanceColor );
  13089. }, 'void' );
  13090. /**
  13091. * TSL function that retrieves the batching color for a given instance ID from a colors texture.
  13092. *
  13093. * @param {Node<texture>} colorsTexture - The colors texture.
  13094. * @param {Node<int>} id - The instance or batch ID.
  13095. * @returns {Node<vec3>} The retrieved color.
  13096. */
  13097. const getBatchingColor = /*@__PURE__*/ Fn( ( [ colorsTexture, id ] ) => {
  13098. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x ).toConst();
  13099. const j = int( id );
  13100. const x = j.mod( size ).toConst();
  13101. const y = j.div( size ).toConst();
  13102. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  13103. } );
  13104. /**
  13105. * TSL function that retrieves the indirect index for a given batch ID.
  13106. *
  13107. * @param {BatchedMesh} batchMesh - The batched mesh.
  13108. * @param {Node<int>} id - The draw or instance ID.
  13109. * @returns {Node<uint>} The indirect index.
  13110. */
  13111. const getIndirectIndex = /*@__PURE__*/ Fn( ( [ indirectTexture, id ] ) => {
  13112. const size = int( textureSize( textureLoad( indirectTexture ), 0 ).x ).toConst();
  13113. const x = int( id ).mod( size ).toConst();
  13114. const y = int( id ).div( size ).toConst();
  13115. return textureLoad( indirectTexture, ivec2( x, y ) ).x;
  13116. } );
  13117. /**
  13118. * TSL object representing a varying property for the batching color vector.
  13119. *
  13120. * @type {VaryingNode<vec3>}
  13121. */
  13122. const batchColor = /*@__PURE__*/ varyingProperty( 'vec3', 'vBatchColor' );
  13123. /**
  13124. * TSL function representing the vertex shader batching setup.
  13125. * Applies the batch transformation matrix to positionLocal, normalLocal, and tangentLocal.
  13126. * Also assigns the batch color if a color texture is present.
  13127. *
  13128. * @tsl
  13129. * @function
  13130. * @param {BatchedMesh} batchMesh - The batched mesh.
  13131. */
  13132. const batch = /*@__PURE__*/ Fn( ( [ batchMesh ], builder ) => {
  13133. const batchingIdNode = builder.getDrawIndex() === null ? instanceIndex : drawIndex;
  13134. const indirectId = getIndirectIndex( batchMesh._indirectTexture, int( batchingIdNode ) );
  13135. const matricesTexture = batchMesh._matricesTexture;
  13136. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x ).toConst();
  13137. const j = float( indirectId ).mul( 4 ).toInt().toConst();
  13138. const x = j.mod( size ).toConst();
  13139. const y = j.div( size ).toConst();
  13140. const batchingMatrix = mat4(
  13141. textureLoad( matricesTexture, ivec2( x, y ) ),
  13142. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  13143. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  13144. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  13145. );
  13146. const colorsTexture = batchMesh._colorsTexture;
  13147. if ( colorsTexture !== null ) {
  13148. const color = getBatchingColor( colorsTexture, indirectId );
  13149. batchColor.assign( color );
  13150. }
  13151. const bm = mat3( batchingMatrix );
  13152. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  13153. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  13154. const batchingNormal = bm.mul( transformedNormal ).xyz;
  13155. normalLocal.assign( batchingNormal );
  13156. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  13157. tangentLocal.mulAssign( bm );
  13158. }
  13159. }, 'void' );
  13160. const _skeletonsUpdated = /*@__PURE__*/ new WeakMap();
  13161. const _previousBoneMatricesData = /*@__PURE__*/ new WeakMap();
  13162. /**
  13163. * Computes the skinned position by applying bone matrices based on weights.
  13164. *
  13165. * @param {Node} boneMatrices - The bone matrices buffer or storage node.
  13166. * @param {Node<vec3>} position - The vertex position to transform.
  13167. * @param {Node<mat4>} bindMatrix - The bind matrix node.
  13168. * @param {Node<mat4>} bindMatrixInverse - The inverse bind matrix node.
  13169. * @param {Node<uvec4>} skinIndex - The skin index attribute.
  13170. * @param {Node<vec4>} skinWeight - The skin weight attribute.
  13171. * @returns {Node<vec3>} The skinned position.
  13172. */
  13173. function getSkinnedPosition( boneMatrices, position, bindMatrix, bindMatrixInverse, skinIndex, skinWeight ) {
  13174. const boneMatX = boneMatrices.element( skinIndex.x );
  13175. const boneMatY = boneMatrices.element( skinIndex.y );
  13176. const boneMatZ = boneMatrices.element( skinIndex.z );
  13177. const boneMatW = boneMatrices.element( skinIndex.w );
  13178. // POSITION
  13179. const skinVertex = bindMatrix.mul( position );
  13180. const skinned = add(
  13181. boneMatX.mul( skinWeight.x ).mul( skinVertex ),
  13182. boneMatY.mul( skinWeight.y ).mul( skinVertex ),
  13183. boneMatZ.mul( skinWeight.z ).mul( skinVertex ),
  13184. boneMatW.mul( skinWeight.w ).mul( skinVertex )
  13185. );
  13186. return bindMatrixInverse.mul( skinned ).xyz;
  13187. }
  13188. /**
  13189. * Computes the skinned normal and tangent vectors by applying bone matrices based on weights.
  13190. *
  13191. * @param {Node} boneMatrices - The bone matrices buffer or storage node.
  13192. * @param {Node<vec3>} normal - The normal vector in local space.
  13193. * @param {Node<vec3>} tangent - The tangent vector in local space.
  13194. * @param {Node<mat4>} bindMatrix - The bind matrix node.
  13195. * @param {Node<mat4>} bindMatrixInverse - The inverse bind matrix node.
  13196. * @param {Node<uvec4>} skinIndex - The skin index attribute.
  13197. * @param {Node<vec4>} skinWeight - The skin weight attribute.
  13198. * @returns {{skinNormal: Node<vec3>, skinTangent: Node<vec3>}} The skinned normal and tangent.
  13199. */
  13200. function getSkinnedNormalAndTangent( boneMatrices, normal, tangent, bindMatrix, bindMatrixInverse, skinIndex, skinWeight ) {
  13201. const boneMatX = boneMatrices.element( skinIndex.x );
  13202. const boneMatY = boneMatrices.element( skinIndex.y );
  13203. const boneMatZ = boneMatrices.element( skinIndex.z );
  13204. const boneMatW = boneMatrices.element( skinIndex.w );
  13205. // NORMAL and TANGENT
  13206. let skinMatrix = add(
  13207. skinWeight.x.mul( boneMatX ),
  13208. skinWeight.y.mul( boneMatY ),
  13209. skinWeight.z.mul( boneMatZ ),
  13210. skinWeight.w.mul( boneMatW )
  13211. );
  13212. skinMatrix = bindMatrixInverse.mul( skinMatrix ).mul( bindMatrix );
  13213. const skinNormal = skinMatrix.transformDirection( normal ).xyz;
  13214. const skinTangent = skinMatrix.transformDirection( tangent ).xyz;
  13215. return { skinNormal, skinTangent };
  13216. }
  13217. /**
  13218. * Retrieves or initializes the previous frame skinned position node for motion vectors.
  13219. * Uses a WeakMap to cache previous frame bone matrix arrays and their TSL buffer nodes.
  13220. *
  13221. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  13222. * @param {Node<mat4>} bindMatrixNode - The bind matrix node.
  13223. * @param {Node<mat4>} bindMatrixInverseNode - The inverse bind matrix node.
  13224. * @param {Node<uvec4>} skinIndexNode - The skin index attribute.
  13225. * @param {Node<vec4>} skinWeightNode - The skin weight attribute.
  13226. * @returns {Node<vec3>} The skinned position from the previous frame.
  13227. */
  13228. function getPreviousSkinnedPosition( skinnedMesh, bindMatrixNode, bindMatrixInverseNode, skinIndexNode, skinWeightNode ) {
  13229. const skeleton = skinnedMesh.skeleton;
  13230. let data = _previousBoneMatricesData.get( skeleton );
  13231. if ( data === undefined ) {
  13232. skeleton.update();
  13233. const previousBoneMatrices = new Float32Array( skeleton.boneMatrices );
  13234. data = {
  13235. previousBoneMatrices,
  13236. node: buffer( previousBoneMatrices, 'mat4', skeleton.bones.length )
  13237. };
  13238. _previousBoneMatricesData.set( skeleton, data );
  13239. }
  13240. return getSkinnedPosition( data.node, positionPrevious, bindMatrixNode, bindMatrixInverseNode, skinIndexNode, skinWeightNode );
  13241. }
  13242. /**
  13243. * TSL function representing the standard skeletal animation vertex shader setup.
  13244. * Transforms positionLocal, normalLocal, and tangentLocal in-place.
  13245. *
  13246. * @tsl
  13247. * @function
  13248. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  13249. */
  13250. const skinning = /*@__PURE__*/ Fn( ( [ skinnedMesh ], builder ) => {
  13251. const skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  13252. const skinWeightNode = attribute( 'skinWeight', 'vec4' );
  13253. const bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  13254. const bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  13255. const boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  13256. OnObjectUpdate( ( { object, frameId } ) => {
  13257. const skeleton = object.skeleton;
  13258. if ( _skeletonsUpdated.get( skeleton ) !== frameId ) {
  13259. _skeletonsUpdated.set( skeleton, frameId );
  13260. const skeletonData = _previousBoneMatricesData.get( skeleton );
  13261. if ( skeletonData !== undefined ) {
  13262. skeletonData.previousBoneMatrices.set( skeleton.boneMatrices );
  13263. }
  13264. skeleton.update();
  13265. }
  13266. } );
  13267. if ( builder.needsPreviousData() ) {
  13268. const previousSkinnedPosition = getPreviousSkinnedPosition( skinnedMesh, bindMatrixNode, bindMatrixInverseNode, skinIndexNode, skinWeightNode );
  13269. positionPrevious.assign( previousSkinnedPosition );
  13270. }
  13271. const skinPosition = getSkinnedPosition( boneMatricesNode, positionLocal, bindMatrixNode, bindMatrixInverseNode, skinIndexNode, skinWeightNode );
  13272. positionLocal.assign( skinPosition );
  13273. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  13274. const { skinNormal, skinTangent } = getSkinnedNormalAndTangent( boneMatricesNode, normalLocal, tangentLocal, bindMatrixNode, bindMatrixInverseNode, skinIndexNode, skinWeightNode );
  13275. normalLocal.assign( skinNormal );
  13276. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  13277. tangentLocal.assign( skinTangent );
  13278. }
  13279. }
  13280. }, 'void' );
  13281. /**
  13282. * TSL function that computes skeletal animation for custom compute passes.
  13283. *
  13284. * @tsl
  13285. * @function
  13286. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  13287. * @param {Node<vec3>} [toPosition=null] - The target position node to assign.
  13288. * @returns {Node<vec3>} The computed skinned position node.
  13289. */
  13290. const computeSkinning = /*@__PURE__*/ Fn( ( [ skinnedMesh, toPosition = null ], builder ) => {
  13291. const positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  13292. const skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  13293. const skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  13294. const bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  13295. const bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  13296. const boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  13297. const skeleton = skinnedMesh.skeleton;
  13298. OnObjectUpdate( ( { frameId } ) => {
  13299. if ( _skeletonsUpdated.get( skeleton ) !== frameId ) {
  13300. _skeletonsUpdated.set( skeleton, frameId );
  13301. const state = _previousBoneMatricesData.get( skeleton );
  13302. if ( state !== undefined ) {
  13303. state.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, positionNode, bindMatrixNode, bindMatrixInverseNode, skinIndexNode, skinWeightNode );
  13313. if ( toPosition !== null ) {
  13314. toPosition.assign( skinPosition );
  13315. }
  13316. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  13317. const { skinNormal, skinTangent } = getSkinnedNormalAndTangent( boneMatricesNode, normalLocal, tangentLocal, bindMatrixNode, bindMatrixInverseNode, skinIndexNode, skinWeightNode );
  13318. normalLocal.assign( skinNormal );
  13319. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  13320. tangentLocal.assign( skinTangent );
  13321. }
  13322. }
  13323. return skinPosition;
  13324. } );
  13325. /**
  13326. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  13327. * ```js
  13328. * Loop( count, ( { i } ) => {
  13329. *
  13330. * } );
  13331. * ```
  13332. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  13333. * ```js
  13334. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  13335. *
  13336. * } );
  13337. *```
  13338. * Nested loops can be defined in a compacted form:
  13339. * ```js
  13340. * Loop( 10, 5, ( { i, j } ) => {
  13341. *
  13342. * } );
  13343. * ```
  13344. * Loops that should run backwards can be defined like so:
  13345. * ```js
  13346. * Loop( { start: 10 }, () => {} );
  13347. * ```
  13348. * It is possible to execute with boolean values, similar to the `while` syntax.
  13349. * ```js
  13350. * const value = float( 0 ).toVar();
  13351. *
  13352. * Loop( value.lessThan( 10 ), () => {
  13353. *
  13354. * value.addAssign( 1 );
  13355. *
  13356. * } );
  13357. * ```
  13358. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  13359. * @augments Node
  13360. */
  13361. class LoopNode extends Node {
  13362. static get type() {
  13363. return 'LoopNode';
  13364. }
  13365. /**
  13366. * Constructs a new loop node.
  13367. *
  13368. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  13369. */
  13370. constructor( params = [] ) {
  13371. super( 'void' );
  13372. this.params = params;
  13373. }
  13374. /**
  13375. * Returns a loop variable name based on an index. The pattern is
  13376. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  13377. *
  13378. * @param {number} index - The index.
  13379. * @return {string} The loop variable name.
  13380. */
  13381. getVarName( index ) {
  13382. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  13383. }
  13384. /**
  13385. * Returns properties about this node.
  13386. *
  13387. * @param {NodeBuilder} builder - The current node builder.
  13388. * @return {Object} The node properties.
  13389. */
  13390. getProperties( builder ) {
  13391. const properties = builder.getNodeProperties( this );
  13392. if ( properties.stackNode !== undefined ) return properties;
  13393. //
  13394. const inputs = {};
  13395. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  13396. const param = this.params[ i ];
  13397. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  13398. const type = ( param.isNode !== true && param.type ) || 'int';
  13399. inputs[ name ] = expression( name, type );
  13400. }
  13401. const stack = builder.addStack();
  13402. const fnCall = this.params[ this.params.length - 1 ]( inputs );
  13403. properties.returnsNode = fnCall.context( { nodeLoop: fnCall } );
  13404. properties.stackNode = stack;
  13405. const baseParam = this.params[ 0 ];
  13406. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  13407. const fnUpdateCall = Fn( this.params[ 0 ].update )( inputs );
  13408. properties.updateNode = fnUpdateCall.context( { nodeLoop: fnUpdateCall } );
  13409. }
  13410. builder.removeStack();
  13411. return properties;
  13412. }
  13413. setup( builder ) {
  13414. // setup properties
  13415. this.getProperties( builder );
  13416. if ( builder.fnCall ) {
  13417. const shaderNodeData = builder.getDataFromNode( builder.fnCall.shaderNode );
  13418. shaderNodeData.hasLoop = true;
  13419. }
  13420. }
  13421. generate( builder ) {
  13422. const properties = this.getProperties( builder );
  13423. const params = this.params;
  13424. const stackNode = properties.stackNode;
  13425. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  13426. const param = params[ i ];
  13427. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  13428. if ( param.isNode ) {
  13429. if ( param.getNodeType( builder ) === 'bool' ) {
  13430. isWhile = true;
  13431. type = 'bool';
  13432. end = param.build( builder, type );
  13433. } else {
  13434. type = 'int';
  13435. name = this.getVarName( i );
  13436. start = '0';
  13437. end = param.build( builder, type );
  13438. condition = '<';
  13439. }
  13440. } else {
  13441. type = param.type || 'int';
  13442. name = param.name || this.getVarName( i );
  13443. start = param.start;
  13444. end = param.end;
  13445. condition = param.condition;
  13446. update = param.update;
  13447. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  13448. else if ( start && start.isNode ) start = start.build( builder, type );
  13449. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  13450. else if ( end && end.isNode ) end = end.build( builder, type );
  13451. if ( start !== undefined && end === undefined ) {
  13452. start = start + ' - 1';
  13453. end = '0';
  13454. condition = '>=';
  13455. } else if ( end !== undefined && start === undefined ) {
  13456. start = '0';
  13457. condition = '<';
  13458. }
  13459. if ( condition === undefined ) {
  13460. if ( Number( start ) > Number( end ) ) {
  13461. condition = '>=';
  13462. } else {
  13463. condition = '<';
  13464. }
  13465. }
  13466. }
  13467. let loopSnippet;
  13468. if ( isWhile ) {
  13469. loopSnippet = `while ( ${ end } )`;
  13470. } else {
  13471. const internalParam = { start, end};
  13472. //
  13473. const startSnippet = internalParam.start;
  13474. const endSnippet = internalParam.end;
  13475. let updateSnippet;
  13476. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  13477. if ( update !== undefined && update !== null ) {
  13478. switch ( typeof update ) {
  13479. case 'function':
  13480. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  13481. const snippet = flow.code.replace( /\t|;/g, '' );
  13482. updateSnippet = snippet;
  13483. break;
  13484. case 'number':
  13485. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  13486. break;
  13487. case 'string':
  13488. updateSnippet = name + ' ' + update;
  13489. break;
  13490. default:
  13491. if ( update.isNode ) {
  13492. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  13493. } else {
  13494. error( 'TSL: \'Loop( { update: ... } )\' is not a function, string or number.', this.stackTrace );
  13495. updateSnippet = 'break /* invalid update */';
  13496. }
  13497. }
  13498. } else {
  13499. if ( type === 'int' || type === 'uint' ) {
  13500. update = condition.includes( '<' ) ? '++' : '--';
  13501. } else {
  13502. update = deltaOperator() + ' 1.';
  13503. }
  13504. updateSnippet = name + ' ' + update;
  13505. }
  13506. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  13507. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  13508. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  13509. }
  13510. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  13511. }
  13512. const stackSnippet = stackNode.build( builder, 'void' );
  13513. properties.returnsNode.build( builder, 'void' );
  13514. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  13515. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  13516. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  13517. }
  13518. builder.addFlowTab();
  13519. }
  13520. }
  13521. /**
  13522. * TSL function for creating a loop node.
  13523. *
  13524. * @tsl
  13525. * @function
  13526. * @param {...any} params - A list of parameters.
  13527. * @returns {LoopNode}
  13528. */
  13529. const Loop = ( ...params ) => new LoopNode( nodeArray( params, 'int' ) ).toStack();
  13530. /**
  13531. * TSL function for creating a `Continue()` expression.
  13532. *
  13533. * @tsl
  13534. * @function
  13535. * @returns {ExpressionNode}
  13536. */
  13537. const Continue = () => expression( 'continue' ).toStack();
  13538. /**
  13539. * TSL function for creating a `Break()` expression.
  13540. *
  13541. * @tsl
  13542. * @function
  13543. * @returns {ExpressionNode}
  13544. */
  13545. const Break = () => expression( 'break' ).toStack();
  13546. const _morphTextures = /*@__PURE__*/ new WeakMap();
  13547. const _morphVec4 = /*@__PURE__*/ new Vector4();
  13548. const _morphInfluencesData = /*@__PURE__*/ new WeakMap();
  13549. /**
  13550. * TSL function that retrieves and scales the morphed attribute (position or normal) texel value.
  13551. *
  13552. * @param {Object} params - The parameter object.
  13553. * @param {Node<texture>} params.bufferMap - The morph target data array texture.
  13554. * @param {Node<float>} params.influence - The target's animation influence weight.
  13555. * @param {number} params.stride - The vertex data stride (e.g. 1 or 2).
  13556. * @param {Node<int>} params.width - The texture width limit.
  13557. * @param {Node<int>} params.depth - The target layer index (morph target index).
  13558. * @param {Node<int>} params.offset - The texture offset (e.g. 0 for position, 1 for normal).
  13559. * @returns {Node<vec3>} The scaled morph target translation value.
  13560. */
  13561. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  13562. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  13563. const y = texelIndex.div( width );
  13564. const x = texelIndex.sub( y.mul( width ) );
  13565. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  13566. return bufferAttrib.mul( influence );
  13567. } );
  13568. /**
  13569. * Resolves or creates a compiled DataArrayTexture containing encoded vertex morph targets data for WebGL2/WebGPU.
  13570. *
  13571. * @param {BufferGeometry} geometry - The geometry to parse.
  13572. * @returns {Object} The resolved morph targets texture data mapping entry.
  13573. */
  13574. function getEntry( geometry ) {
  13575. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  13576. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  13577. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  13578. // instead of using attributes, the WebGL 2 code path encodes morph targets
  13579. // into an array of data textures. Each layer represents a single morph target.
  13580. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  13581. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  13582. let entry = _morphTextures.get( geometry );
  13583. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  13584. if ( entry !== undefined ) entry.texture.dispose();
  13585. const morphTargets = geometry.morphAttributes.position || [];
  13586. const morphNormals = geometry.morphAttributes.normal || [];
  13587. const morphColors = geometry.morphAttributes.color || [];
  13588. let vertexDataCount = 0;
  13589. if ( hasMorphPosition === true ) vertexDataCount = 1;
  13590. if ( hasMorphNormals === true ) vertexDataCount = 2;
  13591. if ( hasMorphColors === true ) vertexDataCount = 3;
  13592. let width = geometry.attributes.position.count * vertexDataCount;
  13593. let height = 1;
  13594. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  13595. if ( width > maxTextureSize ) {
  13596. height = Math.ceil( width / maxTextureSize );
  13597. width = maxTextureSize;
  13598. }
  13599. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  13600. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  13601. bufferTexture.type = FloatType;
  13602. bufferTexture.needsUpdate = true;
  13603. // fill buffer
  13604. const vertexDataStride = vertexDataCount * 4;
  13605. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  13606. const morphTarget = morphTargets[ i ];
  13607. const morphNormal = morphNormals[ i ];
  13608. const morphColor = morphColors[ i ];
  13609. const offset = width * height * 4 * i;
  13610. for ( let j = 0; j < morphTarget.count; j ++ ) {
  13611. const stride = j * vertexDataStride;
  13612. if ( hasMorphPosition === true ) {
  13613. _morphVec4.fromBufferAttribute( morphTarget, j );
  13614. buffer[ offset + stride + 0 ] = _morphVec4.x;
  13615. buffer[ offset + stride + 1 ] = _morphVec4.y;
  13616. buffer[ offset + stride + 2 ] = _morphVec4.z;
  13617. buffer[ offset + stride + 3 ] = 0;
  13618. }
  13619. if ( hasMorphNormals === true ) {
  13620. _morphVec4.fromBufferAttribute( morphNormal, j );
  13621. buffer[ offset + stride + 4 ] = _morphVec4.x;
  13622. buffer[ offset + stride + 5 ] = _morphVec4.y;
  13623. buffer[ offset + stride + 6 ] = _morphVec4.z;
  13624. buffer[ offset + stride + 7 ] = 0;
  13625. }
  13626. if ( hasMorphColors === true ) {
  13627. _morphVec4.fromBufferAttribute( morphColor, j );
  13628. buffer[ offset + stride + 8 ] = _morphVec4.x;
  13629. buffer[ offset + stride + 9 ] = _morphVec4.y;
  13630. buffer[ offset + stride + 10 ] = _morphVec4.z;
  13631. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  13632. }
  13633. }
  13634. }
  13635. entry = {
  13636. count: morphTargetsCount,
  13637. texture: bufferTexture,
  13638. stride: vertexDataCount,
  13639. size: new Vector2( width, height )
  13640. };
  13641. _morphTextures.set( geometry, entry );
  13642. function disposeTexture() {
  13643. bufferTexture.dispose();
  13644. _morphTextures.delete( geometry );
  13645. geometry.removeEventListener( 'dispose', disposeTexture );
  13646. }
  13647. geometry.addEventListener( 'dispose', disposeTexture );
  13648. }
  13649. return entry;
  13650. }
  13651. /**
  13652. * TSL function representing the vertex shader morph targets blend setup.
  13653. * Dynamically computes morph targets weights and updates positionLocal and normalLocal in-place.
  13654. *
  13655. * @tsl
  13656. * @function
  13657. * @param {Mesh} mesh - The mesh.
  13658. */
  13659. const morphReference = /*@__PURE__*/ Fn( ( [ mesh ] ) => {
  13660. const { geometry } = mesh;
  13661. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  13662. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  13663. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  13664. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  13665. if ( morphTargetsCount === 0 ) return;
  13666. // Init
  13667. let morphInfluenceData = _morphInfluencesData.get( mesh );
  13668. if ( morphInfluenceData === undefined || morphInfluenceData.count !== morphTargetsCount ) {
  13669. morphInfluenceData = {
  13670. base: uniform( 1 ),
  13671. influences: mesh.morphTargetInfluences ? uniformArray( mesh.morphTargetInfluences, 'float' ) : null,
  13672. count: morphTargetsCount
  13673. };
  13674. _morphInfluencesData.set( mesh, morphInfluenceData );
  13675. }
  13676. const { base, influences } = morphInfluenceData;
  13677. // Shader
  13678. const { texture: bufferMap, stride, size } = getEntry( geometry );
  13679. if ( hasMorphPosition === true ) positionLocal.mulAssign( base );
  13680. if ( hasMorphNormals === true ) normalLocal.mulAssign( base );
  13681. const width = int( size.width );
  13682. Loop( morphTargetsCount, ( { i } ) => {
  13683. const influence = float( 0 ).toVar();
  13684. if ( mesh.count > 1 && ( mesh.morphTexture !== null && mesh.morphTexture !== undefined ) ) {
  13685. influence.assign( textureLoad( mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  13686. } else {
  13687. influence.assign( influences.element( i ).toVar() );
  13688. }
  13689. If( influence.notEqual( 0 ), () => {
  13690. if ( hasMorphPosition === true ) {
  13691. positionLocal.addAssign( getMorph( {
  13692. bufferMap,
  13693. influence,
  13694. stride,
  13695. width,
  13696. depth: i,
  13697. offset: int( 0 )
  13698. } ) );
  13699. }
  13700. if ( hasMorphNormals === true ) {
  13701. normalLocal.addAssign( getMorph( {
  13702. bufferMap,
  13703. influence,
  13704. stride,
  13705. width,
  13706. depth: i,
  13707. offset: int( 1 )
  13708. } ) );
  13709. }
  13710. } );
  13711. } );
  13712. // Update
  13713. OnObjectUpdate( ( { object } ) => {
  13714. const { base, influences } = morphInfluenceData;
  13715. if ( object.geometry.morphTargetsRelative ) {
  13716. base.value = 1;
  13717. } else {
  13718. base.value = 1 - object.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  13719. }
  13720. if ( influences ) {
  13721. influences.array = object.morphTargetInfluences;
  13722. influences.update();
  13723. }
  13724. } );
  13725. }, 'void' );
  13726. /**
  13727. * Base class for lighting nodes.
  13728. *
  13729. * @augments Node
  13730. */
  13731. class LightingNode extends Node {
  13732. static get type() {
  13733. return 'LightingNode';
  13734. }
  13735. /**
  13736. * Constructs a new lighting node.
  13737. */
  13738. constructor() {
  13739. super( 'vec3' );
  13740. /**
  13741. * This flag can be used for type testing.
  13742. *
  13743. * @type {boolean}
  13744. * @readonly
  13745. * @default true
  13746. */
  13747. this.isLightingNode = true;
  13748. }
  13749. }
  13750. /**
  13751. * A generic class that can be used by nodes which contribute
  13752. * ambient occlusion to the scene. E.g. an ambient occlusion map
  13753. * node can be used as input for this module. Used in {@link NodeMaterial}.
  13754. *
  13755. * @augments LightingNode
  13756. */
  13757. class AONode extends LightingNode {
  13758. static get type() {
  13759. return 'AONode';
  13760. }
  13761. /**
  13762. * Constructs a new AO node.
  13763. *
  13764. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  13765. */
  13766. constructor( aoNode = null ) {
  13767. super();
  13768. /**
  13769. * The ambient occlusion node.
  13770. *
  13771. * @type {?Node<float>}
  13772. * @default null
  13773. */
  13774. this.aoNode = aoNode;
  13775. }
  13776. setup( builder ) {
  13777. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  13778. }
  13779. }
  13780. /**
  13781. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  13782. * by adding lighting specific context data. It represents the runtime context of
  13783. * {@link LightsNode}.
  13784. *
  13785. * @augments ContextNode
  13786. */
  13787. class LightingContextNode extends ContextNode {
  13788. static get type() {
  13789. return 'LightingContextNode';
  13790. }
  13791. /**
  13792. * Constructs a new lighting context node.
  13793. *
  13794. * @param {LightsNode} lightsNode - The lights node.
  13795. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  13796. * @param {?Array<LightingNode>} materialLightings - The material lightings nodes.
  13797. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  13798. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  13799. */
  13800. constructor( lightsNode, lightingModel = null, materialLightings = [], backdropNode = null, backdropAlphaNode = null ) {
  13801. super( lightsNode );
  13802. /**
  13803. * The current lighting model.
  13804. *
  13805. * @type {?LightingModel}
  13806. * @default null
  13807. */
  13808. this.lightingModel = lightingModel;
  13809. /**
  13810. * @type {?Array<LightingNode>}
  13811. * @default []
  13812. */
  13813. this.materialLightings = materialLightings;
  13814. /**
  13815. * A backdrop node.
  13816. *
  13817. * @type {?Node<vec3>}
  13818. * @default null
  13819. */
  13820. this.backdropNode = backdropNode;
  13821. /**
  13822. * A backdrop alpha node.
  13823. *
  13824. * @type {?Node<float>}
  13825. * @default null
  13826. */
  13827. this.backdropAlphaNode = backdropAlphaNode;
  13828. this._value = null;
  13829. }
  13830. /**
  13831. * Returns a lighting context object.
  13832. *
  13833. * @return {{
  13834. * radiance: Node<vec3>,
  13835. * irradiance: Node<vec3>,
  13836. * iblIrradiance: Node<vec3>,
  13837. * ambientOcclusion: Node<float>,
  13838. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  13839. * backdrop: Node<vec3>,
  13840. * backdropAlpha: Node<float>
  13841. * }} The lighting context object.
  13842. */
  13843. getContext() {
  13844. const { materialLightings, backdropNode, backdropAlphaNode } = this;
  13845. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  13846. directSpecular = vec3().toVar( 'directSpecular' ),
  13847. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  13848. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  13849. const reflectedLight = {
  13850. directDiffuse,
  13851. directSpecular,
  13852. indirectDiffuse,
  13853. indirectSpecular
  13854. };
  13855. const context = {
  13856. radiance: vec3().toVar( 'radiance' ),
  13857. irradiance: vec3().toVar( 'irradiance' ),
  13858. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  13859. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  13860. reflectedLight,
  13861. materialLightings,
  13862. backdrop: backdropNode,
  13863. backdropAlpha: backdropAlphaNode
  13864. };
  13865. return context;
  13866. }
  13867. setup( builder ) {
  13868. this.value = this._value || ( this._value = this.getContext() );
  13869. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  13870. return super.setup( builder );
  13871. }
  13872. }
  13873. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  13874. /**
  13875. * A generic class that can be used by nodes which contribute
  13876. * irradiance to the scene. E.g. a light map node can be used
  13877. * as input for this module. Used in {@link NodeMaterial}.
  13878. *
  13879. * @augments LightingNode
  13880. */
  13881. class IrradianceNode extends LightingNode {
  13882. static get type() {
  13883. return 'IrradianceNode';
  13884. }
  13885. /**
  13886. * Constructs a new irradiance node.
  13887. *
  13888. * @param {Node<vec3>} node - A node contributing irradiance.
  13889. */
  13890. constructor( node ) {
  13891. super();
  13892. /**
  13893. * A node contributing irradiance.
  13894. *
  13895. * @type {Node<vec3>}
  13896. */
  13897. this.node = node;
  13898. }
  13899. setup( builder ) {
  13900. builder.context.irradiance.addAssign( this.node );
  13901. }
  13902. }
  13903. const _size$5 = /*@__PURE__*/ new Vector2();
  13904. /**
  13905. * A special type of texture node which represents the data of the current viewport
  13906. * as a texture. The module extracts data from the current bound framebuffer with
  13907. * a copy operation so no extra render pass is required to produce the texture data
  13908. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  13909. * variety of effects like refractive or transmissive materials.
  13910. *
  13911. * @augments TextureNode
  13912. */
  13913. class ViewportTextureNode extends TextureNode {
  13914. static get type() {
  13915. return 'ViewportTextureNode';
  13916. }
  13917. /**
  13918. * Constructs a new viewport texture node.
  13919. *
  13920. * @param {Node} [uvNode=screenUV] - The uv node.
  13921. * @param {?Node} [levelNode=null] - The level node.
  13922. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13923. */
  13924. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  13925. let defaultFramebuffer = null;
  13926. if ( framebufferTexture === null ) {
  13927. defaultFramebuffer = new FramebufferTexture();
  13928. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  13929. framebufferTexture = defaultFramebuffer;
  13930. } else {
  13931. defaultFramebuffer = framebufferTexture;
  13932. }
  13933. super( framebufferTexture, uvNode, levelNode );
  13934. /**
  13935. * Whether to generate mipmaps or not.
  13936. *
  13937. * @type {boolean}
  13938. * @default false
  13939. */
  13940. this.generateMipmaps = false;
  13941. /**
  13942. * The reference framebuffer texture. This is used to store the framebuffer texture
  13943. * for the current render target. If the render target changes, a new framebuffer texture
  13944. * is created automatically.
  13945. *
  13946. * @type {FramebufferTexture}
  13947. * @default null
  13948. */
  13949. this.defaultFramebuffer = defaultFramebuffer;
  13950. /**
  13951. * This flag can be used for type testing.
  13952. *
  13953. * @type {boolean}
  13954. * @readonly
  13955. * @default true
  13956. */
  13957. this.isOutputTextureNode = true;
  13958. /**
  13959. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node should extract
  13960. * the current contents of the bound framebuffer for each render call.
  13961. *
  13962. * @type {string}
  13963. * @default 'render'
  13964. */
  13965. this.updateBeforeType = NodeUpdateType.RENDER;
  13966. /**
  13967. * The framebuffer texture for the current renderer context.
  13968. *
  13969. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  13970. * @private
  13971. */
  13972. this._cacheTextures = new WeakMap();
  13973. }
  13974. /**
  13975. * This methods returns a texture for the given render target or canvas target reference.
  13976. *
  13977. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  13978. * for different render contexts.
  13979. *
  13980. * @param {?(RenderTarget|CanvasTarget)} [reference=null] - The render target or canvas target reference.
  13981. * @return {Texture} The framebuffer texture.
  13982. */
  13983. getTextureForReference( reference = null ) {
  13984. let defaultFramebuffer;
  13985. let cacheTextures;
  13986. if ( this.referenceNode ) {
  13987. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  13988. cacheTextures = this.referenceNode._cacheTextures;
  13989. } else {
  13990. defaultFramebuffer = this.defaultFramebuffer;
  13991. cacheTextures = this._cacheTextures;
  13992. }
  13993. if ( reference === null ) {
  13994. return defaultFramebuffer;
  13995. }
  13996. if ( cacheTextures.has( reference ) === false ) {
  13997. const framebufferTexture = defaultFramebuffer.clone();
  13998. cacheTextures.set( reference, framebufferTexture );
  13999. }
  14000. return cacheTextures.get( reference );
  14001. }
  14002. updateReference( frame ) {
  14003. const renderer = frame.renderer;
  14004. const renderTarget = renderer.getRenderTarget();
  14005. const canvasTarget = renderer.getCanvasTarget();
  14006. const reference = renderTarget ? renderTarget : canvasTarget;
  14007. this.value = this.getTextureForReference( reference );
  14008. return this.value;
  14009. }
  14010. updateBefore( frame ) {
  14011. const renderer = frame.renderer;
  14012. const renderTarget = renderer.getRenderTarget();
  14013. const canvasTarget = renderer.getCanvasTarget();
  14014. const reference = renderTarget ? renderTarget : canvasTarget;
  14015. if ( reference === null ) {
  14016. renderer.getDrawingBufferSize( _size$5 );
  14017. } else if ( reference.getDrawingBufferSize ) {
  14018. reference.getDrawingBufferSize( _size$5 );
  14019. } else {
  14020. _size$5.set( reference.width, reference.height );
  14021. }
  14022. //
  14023. const framebufferTexture = this.getTextureForReference( reference );
  14024. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  14025. framebufferTexture.image.width = _size$5.width;
  14026. framebufferTexture.image.height = _size$5.height;
  14027. framebufferTexture.needsUpdate = true;
  14028. }
  14029. //
  14030. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  14031. framebufferTexture.generateMipmaps = this.generateMipmaps;
  14032. renderer.copyFramebufferToTexture( framebufferTexture );
  14033. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  14034. }
  14035. clone() {
  14036. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  14037. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  14038. return viewportTextureNode;
  14039. }
  14040. }
  14041. /**
  14042. * TSL function for creating a viewport texture node.
  14043. *
  14044. * @tsl
  14045. * @function
  14046. * @param {?Node} [uvNode=screenUV] - The uv node.
  14047. * @param {?Node} [levelNode=null] - The level node.
  14048. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  14049. * @returns {ViewportTextureNode}
  14050. */
  14051. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  14052. /**
  14053. * TSL function for creating a viewport texture node with enabled mipmap generation.
  14054. *
  14055. * @tsl
  14056. * @function
  14057. * @param {?Node} [uvNode=screenUV] - The uv node.
  14058. * @param {?Node} [levelNode=null] - The level node.
  14059. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  14060. * @returns {ViewportTextureNode}
  14061. */
  14062. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  14063. // Singleton instances for common usage
  14064. const _singletonOpaqueViewportTextureNode = /*@__PURE__*/ viewportMipTexture();
  14065. /**
  14066. * TSL function for creating a viewport texture node with enabled mipmap generation.
  14067. * The texture should only contain the opaque rendering objects.
  14068. *
  14069. * This should be used just in transparent or transmissive materials.
  14070. *
  14071. * @tsl
  14072. * @function
  14073. * @param {?Node} [uv=screenUV] - The uv node.
  14074. * @param {?Node} [level=null] - The level node.
  14075. * @returns {ViewportTextureNode}
  14076. */
  14077. const viewportOpaqueMipTexture = ( uv = screenUV, level = null ) => _singletonOpaqueViewportTextureNode.sample( uv, level ); // TODO: Use once() when sample() supports it
  14078. let _sharedDepthbuffer = null;
  14079. /**
  14080. * Represents the depth of the current viewport as a texture. This module
  14081. * can be used in combination with viewport texture to achieve effects
  14082. * that require depth evaluation.
  14083. *
  14084. * @augments ViewportTextureNode
  14085. */
  14086. class ViewportDepthTextureNode extends ViewportTextureNode {
  14087. static get type() {
  14088. return 'ViewportDepthTextureNode';
  14089. }
  14090. /**
  14091. * Constructs a new viewport depth texture node.
  14092. *
  14093. * @param {Node} [uvNode=screenUV] - The uv node.
  14094. * @param {?Node} [levelNode=null] - The level node.
  14095. * @param {?DepthTexture} [depthTexture=null] - A depth texture. If not provided, uses a shared depth texture.
  14096. */
  14097. constructor( uvNode = screenUV, levelNode = null, depthTexture = null ) {
  14098. if ( depthTexture === null ) {
  14099. if ( _sharedDepthbuffer === null ) {
  14100. _sharedDepthbuffer = new DepthTexture();
  14101. }
  14102. depthTexture = _sharedDepthbuffer;
  14103. }
  14104. super( uvNode, levelNode, depthTexture );
  14105. }
  14106. }
  14107. /**
  14108. * TSL function for a viewport depth texture node.
  14109. *
  14110. * @tsl
  14111. * @function
  14112. * @param {?Node} [uvNode=screenUV] - The uv node.
  14113. * @param {?Node} [levelNode=null] - The level node.
  14114. * @param {?DepthTexture} [depthTexture=null] - A depth texture. If not provided, a depth texture is created automatically.
  14115. * @returns {ViewportDepthTextureNode}
  14116. */
  14117. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 3 );
  14118. /**
  14119. * This node offers a collection of features in context of the depth logic in the fragment shader.
  14120. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  14121. * fragment or for depth evaluation purposes.
  14122. *
  14123. * @augments Node
  14124. */
  14125. class ViewportDepthNode extends Node {
  14126. static get type() {
  14127. return 'ViewportDepthNode';
  14128. }
  14129. /**
  14130. * Constructs a new viewport depth node.
  14131. *
  14132. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  14133. * @param {?Node} [valueNode=null] - The value node.
  14134. */
  14135. constructor( scope, valueNode = null ) {
  14136. super( 'float' );
  14137. /**
  14138. * The node behaves differently depending on which scope is selected.
  14139. *
  14140. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  14141. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  14142. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  14143. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  14144. *
  14145. * @type {('depth'|'depthBase'|'linearDepth')}
  14146. */
  14147. this.scope = scope;
  14148. /**
  14149. * Can be used to define a custom depth value.
  14150. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  14151. *
  14152. * @type {?Node}
  14153. * @default null
  14154. */
  14155. this.valueNode = valueNode;
  14156. /**
  14157. * This flag can be used for type testing.
  14158. *
  14159. * @type {boolean}
  14160. * @readonly
  14161. * @default true
  14162. */
  14163. this.isViewportDepthNode = true;
  14164. }
  14165. generate( builder ) {
  14166. const { scope } = this;
  14167. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  14168. return builder.getFragDepth();
  14169. }
  14170. return super.generate( builder );
  14171. }
  14172. setup( { camera } ) {
  14173. const { scope } = this;
  14174. const value = this.valueNode;
  14175. let node = null;
  14176. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  14177. if ( value !== null ) {
  14178. node = depthBase().assign( value );
  14179. }
  14180. } else if ( scope === ViewportDepthNode.DEPTH ) {
  14181. if ( camera.isPerspectiveCamera ) {
  14182. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  14183. } else {
  14184. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14185. }
  14186. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  14187. if ( value !== null ) {
  14188. if ( camera.isPerspectiveCamera ) {
  14189. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  14190. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  14191. } else {
  14192. node = value;
  14193. }
  14194. } else {
  14195. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14196. }
  14197. }
  14198. return node;
  14199. }
  14200. }
  14201. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  14202. ViewportDepthNode.DEPTH = 'depth';
  14203. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  14204. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  14205. /**
  14206. * TSL function for converting a viewZ value to an orthographic depth value.
  14207. *
  14208. * @tsl
  14209. * @function
  14210. * @param {Node<float>} viewZ - The viewZ node.
  14211. * @param {Node<float>} near - The camera's near value.
  14212. * @param {Node<float>} far - The camera's far value.
  14213. * @returns {Node<float>}
  14214. */
  14215. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  14216. /**
  14217. * TSL function for converting a viewZ value to a reversed orthographic depth value.
  14218. *
  14219. * @tsl
  14220. * @function
  14221. * @param {Node<float>} viewZ - The viewZ node.
  14222. * @param {Node<float>} near - The camera's near value.
  14223. * @param {Node<float>} far - The camera's far value.
  14224. * @returns {Node<float>}
  14225. */
  14226. const viewZToReversedOrthographicDepth = ( viewZ, near, far ) => viewZ.add( far ).div( far.sub( near ) );
  14227. /**
  14228. * TSL function for converting an orthographic depth value to a viewZ value.
  14229. *
  14230. * @tsl
  14231. * @function
  14232. * @param {Node<float>} depth - The orthographic depth.
  14233. * @param {Node<float>} near - The camera's near value.
  14234. * @param {Node<float>} far - The camera's far value.
  14235. * @returns {Node<float>}
  14236. */
  14237. const orthographicDepthToViewZ = /*@__PURE__*/ Fn( ( [ depth, near, far ], builder ) => {
  14238. if ( builder.renderer.reversedDepthBuffer === true ) {
  14239. return far.sub( near ).mul( depth ).sub( far );
  14240. } else {
  14241. return near.sub( far ).mul( depth ).sub( near );
  14242. }
  14243. } );
  14244. /**
  14245. * TSL function for converting a viewZ value to a perspective depth value.
  14246. *
  14247. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  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 viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  14257. /**
  14258. * TSL function for converting a viewZ value to a reversed perspective 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 viewZToReversedPerspectiveDepth = ( viewZ, near, far ) => near.mul( viewZ.add( far ) ).div( viewZ.mul( near.sub( far ) ) );
  14268. /**
  14269. * TSL function for converting a perspective depth value to a viewZ value.
  14270. *
  14271. * @tsl
  14272. * @function
  14273. * @param {Node<float>} depth - The perspective 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 perspectiveDepthToViewZ = /*@__PURE__*/ Fn( ( [ depth, near, far ], builder ) => {
  14279. if ( builder.renderer.reversedDepthBuffer === true ) {
  14280. return near.mul( far ).div( near.sub( far ).mul( depth ).sub( near ) );
  14281. } else {
  14282. return near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  14283. }
  14284. } );
  14285. /**
  14286. * TSL function for converting a viewZ value to a logarithmic depth value.
  14287. *
  14288. * @tsl
  14289. * @function
  14290. * @param {Node<float>} viewZ - The viewZ node.
  14291. * @param {Node<float>} near - The camera's near value.
  14292. * @param {Node<float>} far - The camera's far value.
  14293. * @returns {Node<float>}
  14294. */
  14295. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  14296. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  14297. // The final logarithmic depth formula used here is adapted from one described in an
  14298. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  14299. // which was an improvement upon an earlier formula one described in an
  14300. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  14301. // Ulrich's formula is the following:
  14302. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  14303. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  14304. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  14305. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  14306. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  14307. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  14308. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  14309. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  14310. // be used, and ultimately Ulrich's "near plane" version was chosen.
  14311. // Outerra eventually made another improvement to their original "C-constant" variant,
  14312. // but it still does not incorporate the camera near plane (for this version,
  14313. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  14314. // Here we make 4 changes to Ulrich's formula:
  14315. // 1. Clamp the camera near plane so we don't divide by 0.
  14316. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  14317. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  14318. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  14319. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  14320. // so we do the same here, hence the 'viewZ.negate()' call.
  14321. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  14322. near = near.max( 1e-6 ).toVar();
  14323. const numerator = log2( viewZ.negate().div( near ) );
  14324. const denominator = log2( far.div( near ) );
  14325. return numerator.div( denominator );
  14326. };
  14327. /**
  14328. * TSL function for converting a logarithmic depth value to a viewZ value.
  14329. *
  14330. * @tsl
  14331. * @function
  14332. * @param {Node<float>} depth - The logarithmic depth.
  14333. * @param {Node<float>} near - The camera's near value.
  14334. * @param {Node<float>} far - The camera's far value.
  14335. * @returns {Node<float>}
  14336. */
  14337. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  14338. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  14339. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  14340. // a negative viewZ).
  14341. const exponent = depth.mul( log( far.div( near ) ) );
  14342. return float( Math.E ).pow( exponent ).mul( near ).negate();
  14343. };
  14344. /**
  14345. * TSL function for defining a value for the current fragment's depth.
  14346. *
  14347. * @tsl
  14348. * @function
  14349. * @param {Node<float>} value - The depth value to set.
  14350. * @returns {ViewportDepthNode<float>}
  14351. */
  14352. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  14353. /**
  14354. * TSL object that represents the depth value for the current fragment.
  14355. *
  14356. * @tsl
  14357. * @type {ViewportDepthNode}
  14358. */
  14359. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  14360. /**
  14361. * TSL function for converting a perspective depth value to linear depth.
  14362. *
  14363. * @tsl
  14364. * @function
  14365. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  14366. * @returns {ViewportDepthNode<float>}
  14367. */
  14368. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  14369. /**
  14370. * TSL object that represents the linear (orthographic) depth value of the current fragment
  14371. *
  14372. * @tsl
  14373. * @type {ViewportDepthNode}
  14374. */
  14375. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  14376. depth.assign = ( value ) => depthBase( value );
  14377. /**
  14378. * This node is used in {@link NodeMaterial} to setup the clipping
  14379. * which can happen hardware-accelerated (if supported) and optionally
  14380. * use alpha-to-coverage for anti-aliasing clipped edges.
  14381. *
  14382. * @augments Node
  14383. */
  14384. class ClippingNode extends Node {
  14385. static get type() {
  14386. return 'ClippingNode';
  14387. }
  14388. /**
  14389. * Constructs a new clipping node.
  14390. *
  14391. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  14392. * the selected scope influences the behavior of the node and what type of code is generated.
  14393. */
  14394. constructor( scope = ClippingNode.DEFAULT ) {
  14395. super();
  14396. /**
  14397. * The node's scope. Similar to other nodes, the selected scope influences
  14398. * the behavior of the node and what type of code is generated.
  14399. *
  14400. * @type {('default'|'hardware'|'alphaToCoverage')}
  14401. */
  14402. this.scope = scope;
  14403. }
  14404. /**
  14405. * Setups the node depending on the selected scope.
  14406. *
  14407. * @param {NodeBuilder} builder - The current node builder.
  14408. * @return {Node} The result node.
  14409. */
  14410. setup( builder ) {
  14411. super.setup( builder );
  14412. const clippingContext = builder.clippingContext;
  14413. const { intersectionPlanes, unionPlanes } = clippingContext;
  14414. this.hardwareClipping = builder.hardwareClipping;
  14415. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  14416. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  14417. } else if ( this.scope === ClippingNode.HARDWARE ) {
  14418. return this.setupHardwareClipping( unionPlanes, builder );
  14419. } else {
  14420. return this.setupDefault( intersectionPlanes, unionPlanes );
  14421. }
  14422. }
  14423. /**
  14424. * Setups alpha to coverage.
  14425. *
  14426. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  14427. * @param {Array<Vector4>} unionPlanes - The union planes.
  14428. * @return {Node} The result node.
  14429. */
  14430. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  14431. return Fn( () => {
  14432. const distanceToPlane = float().toVar( 'distanceToPlane' );
  14433. const distanceGradient = float().toVar( 'distanceToGradient' );
  14434. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  14435. const numUnionPlanes = unionPlanes.length;
  14436. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  14437. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  14438. Loop( numUnionPlanes, ( { i } ) => {
  14439. const plane = clippingPlanes.element( i );
  14440. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  14441. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  14442. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  14443. } );
  14444. }
  14445. const numIntersectionPlanes = intersectionPlanes.length;
  14446. if ( numIntersectionPlanes > 0 ) {
  14447. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  14448. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  14449. Loop( numIntersectionPlanes, ( { i } ) => {
  14450. const plane = clippingPlanes.element( i );
  14451. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  14452. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  14453. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  14454. } );
  14455. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  14456. }
  14457. diffuseColor.a.mulAssign( clipOpacity );
  14458. diffuseColor.a.equal( 0.0 ).discard();
  14459. } )();
  14460. }
  14461. /**
  14462. * Setups the default clipping.
  14463. *
  14464. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  14465. * @param {Array<Vector4>} unionPlanes - The union planes.
  14466. * @return {Node} The result node.
  14467. */
  14468. setupDefault( intersectionPlanes, unionPlanes ) {
  14469. return Fn( () => {
  14470. const numUnionPlanes = unionPlanes.length;
  14471. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  14472. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  14473. Loop( numUnionPlanes, ( { i } ) => {
  14474. const plane = clippingPlanes.element( i );
  14475. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  14476. } );
  14477. }
  14478. const numIntersectionPlanes = intersectionPlanes.length;
  14479. if ( numIntersectionPlanes > 0 ) {
  14480. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  14481. const clipped = bool( true ).toVar( 'clipped' );
  14482. Loop( numIntersectionPlanes, ( { i } ) => {
  14483. const plane = clippingPlanes.element( i );
  14484. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  14485. } );
  14486. clipped.discard();
  14487. }
  14488. } )();
  14489. }
  14490. /**
  14491. * Setups hardware clipping.
  14492. *
  14493. * @param {Array<Vector4>} unionPlanes - The union planes.
  14494. * @param {NodeBuilder} builder - The current node builder.
  14495. * @return {Node} The result node.
  14496. */
  14497. setupHardwareClipping( unionPlanes, builder ) {
  14498. const numUnionPlanes = unionPlanes.length;
  14499. builder.enableHardwareClipping( numUnionPlanes );
  14500. return Fn( () => {
  14501. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  14502. const hw_clip_distances = builtin( builder.getClipDistance() );
  14503. Loop( numUnionPlanes, ( { i } ) => {
  14504. const plane = clippingPlanes.element( i );
  14505. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  14506. hw_clip_distances.element( i ).assign( distance );
  14507. } );
  14508. } )();
  14509. }
  14510. }
  14511. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  14512. ClippingNode.DEFAULT = 'default';
  14513. ClippingNode.HARDWARE = 'hardware';
  14514. /**
  14515. * TSL function for setting up the default clipping logic.
  14516. *
  14517. * @tsl
  14518. * @function
  14519. * @returns {ClippingNode}
  14520. */
  14521. const clipping = () => new ClippingNode();
  14522. /**
  14523. * TSL function for setting up alpha to coverage.
  14524. *
  14525. * @tsl
  14526. * @function
  14527. * @returns {ClippingNode}
  14528. */
  14529. const clippingAlpha = () => new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE );
  14530. /**
  14531. * TSL function for setting up hardware-based clipping.
  14532. *
  14533. * @tsl
  14534. * @function
  14535. * @returns {ClippingNode}
  14536. */
  14537. const hardwareClipping = () => new ClippingNode( ClippingNode.HARDWARE );
  14538. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  14539. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  14540. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  14541. 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 ) ) ) ) ) );
  14542. } );
  14543. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  14544. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  14545. } );
  14546. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  14547. // Find the discretized derivatives of our coordinates
  14548. const maxDeriv = max$1(
  14549. length( dFdx( position.xyz ) ),
  14550. length( dFdy( position.xyz ) )
  14551. );
  14552. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  14553. // Find two nearest log-discretized noise scales
  14554. const pixScales = vec2(
  14555. exp2( floor( log2( pixScale ) ) ),
  14556. exp2( ceil( log2( pixScale ) ) )
  14557. );
  14558. // Compute alpha thresholds at our two noise scales
  14559. const alpha = vec2(
  14560. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  14561. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  14562. );
  14563. // Factor to interpolate lerp with
  14564. const lerpFactor = fract( log2( pixScale ) );
  14565. // Interpolate alpha threshold from noise at two scales
  14566. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  14567. // Pass into CDF to compute uniformly distrib threshold
  14568. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  14569. const cases = vec3(
  14570. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  14571. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  14572. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  14573. // Find our final, uniformly distributed alpha threshold (ατ)
  14574. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  14575. // Avoids ατ == 0. Could also do ατ =1-ατ
  14576. return clamp( threshold, 1.0e-6, 1.0 );
  14577. } ).setLayout( {
  14578. name: 'getAlphaHashThreshold',
  14579. type: 'float',
  14580. inputs: [
  14581. { name: 'position', type: 'vec3' }
  14582. ]
  14583. } );
  14584. /**
  14585. * An attribute node for representing vertex colors.
  14586. *
  14587. * @augments AttributeNode
  14588. */
  14589. class VertexColorNode extends AttributeNode {
  14590. static get type() {
  14591. return 'VertexColorNode';
  14592. }
  14593. /**
  14594. * Constructs a new vertex color node.
  14595. *
  14596. * @param {number} index - The attribute index.
  14597. */
  14598. constructor( index ) {
  14599. super( null, 'vec4' );
  14600. /**
  14601. * This flag can be used for type testing.
  14602. *
  14603. * @type {boolean}
  14604. * @readonly
  14605. * @default true
  14606. */
  14607. this.isVertexColorNode = true;
  14608. /**
  14609. * The attribute index to enable more than one sets of vertex colors.
  14610. *
  14611. * @type {number}
  14612. * @default 0
  14613. */
  14614. this.index = index;
  14615. }
  14616. /**
  14617. * Overwrites the default implementation by honoring the attribute index.
  14618. *
  14619. * @param {NodeBuilder} builder - The current node builder.
  14620. * @return {string} The attribute name.
  14621. */
  14622. getAttributeName( /*builder*/ ) {
  14623. const index = this.index;
  14624. return 'color' + ( index > 0 ? index : '' );
  14625. }
  14626. generate( builder ) {
  14627. const attributeName = this.getAttributeName( builder );
  14628. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  14629. let result;
  14630. if ( geometryAttribute === true ) {
  14631. result = super.generate( builder );
  14632. } else {
  14633. // Vertex color fallback should be white
  14634. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  14635. }
  14636. return result;
  14637. }
  14638. serialize( data ) {
  14639. super.serialize( data );
  14640. data.index = this.index;
  14641. }
  14642. deserialize( data ) {
  14643. super.deserialize( data );
  14644. this.index = data.index;
  14645. }
  14646. }
  14647. /**
  14648. * TSL function for creating a reference node.
  14649. *
  14650. * @tsl
  14651. * @function
  14652. * @param {number} [index=0] - The attribute index.
  14653. * @returns {VertexColorNode}
  14654. */
  14655. const vertexColor = ( index = 0 ) => new VertexColorNode( index );
  14656. /**
  14657. * Base class for all node materials.
  14658. *
  14659. * @augments Material
  14660. */
  14661. class NodeMaterial extends Material {
  14662. static get type() {
  14663. return 'NodeMaterial';
  14664. }
  14665. /**
  14666. * Represents the type of the node material.
  14667. *
  14668. * @type {string}
  14669. */
  14670. get type() {
  14671. return this.constructor.type;
  14672. }
  14673. set type( _value ) { /* */ }
  14674. /**
  14675. * Constructs a new node material.
  14676. */
  14677. constructor() {
  14678. super();
  14679. /**
  14680. * This flag can be used for type testing.
  14681. *
  14682. * @type {boolean}
  14683. * @readonly
  14684. * @default true
  14685. */
  14686. this.isNodeMaterial = true;
  14687. /**
  14688. * Whether this material is affected by fog or not.
  14689. *
  14690. * @type {boolean}
  14691. * @default true
  14692. */
  14693. this.fog = true;
  14694. /**
  14695. * Whether this material is affected by lights or not.
  14696. *
  14697. * @type {boolean}
  14698. * @default false
  14699. */
  14700. this.lights = false;
  14701. /**
  14702. * Node materials which set their `lights` property to `true`
  14703. * are affected by all lights of the scene. Sometimes selective
  14704. * lighting is wanted which means only _some_ lights in the scene
  14705. * affect a material. This can be achieved by creating an instance
  14706. * of {@link LightsNode} with a list of selective
  14707. * lights and assign the node to this property.
  14708. *
  14709. * ```js
  14710. * const customLightsNode = lights( [ light1, light2 ] );
  14711. * material.lightsNode = customLightsNode;
  14712. * ```
  14713. *
  14714. * @type {?LightsNode}
  14715. * @default null
  14716. */
  14717. this.lightsNode = null;
  14718. /**
  14719. * The environment of node materials can be defined by an environment
  14720. * map assigned to the `envMap` property or by `Scene.environment`
  14721. * if the node material is a PBR material. This node property allows to overwrite
  14722. * the default behavior and define the environment with a custom node.
  14723. *
  14724. * ```js
  14725. * material.envNode = pmremTexture( renderTarget.texture );
  14726. * ```
  14727. *
  14728. * @type {?Node<vec3>}
  14729. * @default null
  14730. */
  14731. this.envNode = null;
  14732. /**
  14733. * The lighting of node materials might be influenced by ambient occlusion.
  14734. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  14735. * and the respective `aoMapIntensity`. This node property allows to overwrite
  14736. * the default and define the ambient occlusion with a custom node instead.
  14737. *
  14738. * If you don't want to overwrite the diffuse color but modify the existing
  14739. * values instead, use {@link materialAO}.
  14740. *
  14741. * @type {?Node<float>}
  14742. * @default null
  14743. */
  14744. this.aoNode = null;
  14745. /**
  14746. * The diffuse color of node materials is by default inferred from the
  14747. * `color` and `map` properties. This node property allows to overwrite the default
  14748. * and define the diffuse color with a node instead.
  14749. *
  14750. * ```js
  14751. * material.colorNode = color( 0xff0000 ); // define red color
  14752. * ```
  14753. *
  14754. * If you don't want to overwrite the diffuse color but modify the existing
  14755. * values instead, use {@link materialColor}.
  14756. *
  14757. * ```js
  14758. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  14759. * ```
  14760. *
  14761. * @type {?Node<vec3>}
  14762. * @default null
  14763. */
  14764. this.colorNode = null;
  14765. /**
  14766. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  14767. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  14768. * and define the normals with a node instead.
  14769. *
  14770. * If you don't want to overwrite the normals but modify the existing values instead,
  14771. * use {@link materialNormal}.
  14772. *
  14773. * @type {?Node<vec3>}
  14774. * @default null
  14775. */
  14776. this.normalNode = null;
  14777. /**
  14778. * The opacity of node materials is by default inferred from the `opacity`
  14779. * and `alphaMap` properties. This node property allows to overwrite the default
  14780. * and define the opacity with a node instead.
  14781. *
  14782. * If you don't want to overwrite the opacity but modify the existing
  14783. * value instead, use {@link materialOpacity}.
  14784. *
  14785. * @type {?Node<float>}
  14786. * @default null
  14787. */
  14788. this.opacityNode = null;
  14789. /**
  14790. * This node can be used to implement a variety of filter-like effects. The idea is
  14791. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  14792. * to create an arbitrary effect and then assign the node composition to this property.
  14793. * Everything behind the object using this material will now be affected by a filter.
  14794. *
  14795. * ```js
  14796. * const material = new NodeMaterial()
  14797. * material.transparent = true;
  14798. *
  14799. * // everything behind the object will be monochromatic
  14800. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  14801. * ```
  14802. *
  14803. * Backdrop computations are part of the lighting so only lit materials can use this property.
  14804. *
  14805. * @type {?Node<vec3>}
  14806. * @default null
  14807. */
  14808. this.backdropNode = null;
  14809. /**
  14810. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  14811. *
  14812. * @type {?Node<float>}
  14813. * @default null
  14814. */
  14815. this.backdropAlphaNode = null;
  14816. /**
  14817. * The alpha test of node materials is by default inferred from the `alphaTest`
  14818. * property. This node property allows to overwrite the default and define the
  14819. * alpha test with a node instead.
  14820. *
  14821. * If you don't want to overwrite the alpha test but modify the existing
  14822. * value instead, use {@link materialAlphaTest}.
  14823. *
  14824. * @type {?Node<float>}
  14825. * @default null
  14826. */
  14827. this.alphaTestNode = null;
  14828. /**
  14829. * Discards the fragment if the mask value is `false`.
  14830. *
  14831. * @type {?Node<bool>}
  14832. * @default null
  14833. */
  14834. this.maskNode = null;
  14835. /**
  14836. * This node can be used to implement a shadow mask for the material.
  14837. *
  14838. * @type {?Node<bool>}
  14839. * @default null
  14840. */
  14841. this.maskShadowNode = null;
  14842. /**
  14843. * The local vertex positions are computed based on multiple factors like the
  14844. * attribute data, morphing or skinning. This node property allows to overwrite
  14845. * the default and define local vertex positions with nodes instead.
  14846. *
  14847. * If you don't want to overwrite the vertex positions but modify the existing
  14848. * values instead, use {@link positionLocal}.
  14849. *
  14850. *```js
  14851. * material.positionNode = positionLocal.add( displace );
  14852. * ```
  14853. *
  14854. * @type {?Node<vec3>}
  14855. * @default null
  14856. */
  14857. this.positionNode = null;
  14858. /**
  14859. * This node property is intended for logic which modifies geometry data once or per animation step.
  14860. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  14861. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  14862. * can be implemented.
  14863. *
  14864. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  14865. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  14866. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  14867. * eventually assigned to `geometryNode`.
  14868. *
  14869. * @type {?Function}
  14870. * @default null
  14871. */
  14872. this.geometryNode = null;
  14873. /**
  14874. * Allows to overwrite depth values in the fragment shader.
  14875. *
  14876. * @type {?Node<float>}
  14877. * @default null
  14878. */
  14879. this.depthNode = null;
  14880. /**
  14881. * Allows to overwrite the position used for shadow map rendering which
  14882. * is by default {@link positionWorld}, the vertex position
  14883. * in world space.
  14884. *
  14885. * @type {?Node<float>}
  14886. * @default null
  14887. */
  14888. this.receivedShadowPositionNode = null;
  14889. /**
  14890. * Allows to overwrite the geometry position used for shadow map projection which
  14891. * is by default {@link positionLocal}, the vertex position in local space.
  14892. *
  14893. * @type {?Node<float>}
  14894. * @default null
  14895. */
  14896. this.castShadowPositionNode = null;
  14897. /**
  14898. * This node can be used to influence how an object using this node material
  14899. * receive shadows.
  14900. *
  14901. * ```js
  14902. * const totalShadows = float( 1 ).toVar();
  14903. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  14904. * totalShadows.mulAssign( shadow );
  14905. * //return float( 1 ); // bypass received shadows
  14906. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  14907. * } );
  14908. *
  14909. * @type {?(Function|FunctionNode<vec4>)}
  14910. * @default null
  14911. */
  14912. this.receivedShadowNode = null;
  14913. /**
  14914. * This node can be used to influence how an object using this node material
  14915. * casts shadows. To apply a color to shadows, you can simply do:
  14916. *
  14917. * ```js
  14918. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  14919. * ```
  14920. *
  14921. * Which can be nice to fake colored shadows of semi-transparent objects. It
  14922. * is also common to use the property with `Fn` function so checks are performed
  14923. * per fragment.
  14924. *
  14925. * ```js
  14926. * materialCustomShadow.castShadowNode = Fn( () => {
  14927. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  14928. * return materialColor;
  14929. * } )();
  14930. * ```
  14931. *
  14932. * @type {?Node<vec4>}
  14933. * @default null
  14934. */
  14935. this.castShadowNode = null;
  14936. /**
  14937. * This node can be used to define the final output of the material.
  14938. *
  14939. * TODO: Explain the differences to `fragmentNode`.
  14940. *
  14941. * @type {?Node<vec4>}
  14942. * @default null
  14943. */
  14944. this.outputNode = null;
  14945. /**
  14946. * MRT configuration is done on renderer or pass level. This node allows to
  14947. * overwrite what values are written into MRT targets on material level. This
  14948. * can be useful for implementing selective FX features that should only affect
  14949. * specific objects.
  14950. *
  14951. * @type {?MRTNode}
  14952. * @default null
  14953. */
  14954. this.mrtNode = null;
  14955. /**
  14956. * This node property can be used if you need complete freedom in implementing
  14957. * the fragment shader. Assigning a node will replace the built-in material
  14958. * logic used in the fragment stage.
  14959. *
  14960. * @type {?Node<vec4>}
  14961. * @default null
  14962. */
  14963. this.fragmentNode = null;
  14964. /**
  14965. * This node property can be used if you need complete freedom in implementing
  14966. * the vertex shader. Assigning a node will replace the built-in material logic
  14967. * used in the vertex stage.
  14968. *
  14969. * @type {?Node<vec4>}
  14970. * @default null
  14971. */
  14972. this.vertexNode = null;
  14973. /**
  14974. * This node can be used as a global context management component for this material.
  14975. *
  14976. * @type {?ContextNode}
  14977. * @default null
  14978. */
  14979. this.contextNode = null;
  14980. }
  14981. /**
  14982. * Returns an array of child nodes for this material.
  14983. *
  14984. * @private
  14985. * @returns {Array<{property: string, childNode: Node}>}
  14986. */
  14987. _getNodeChildren() {
  14988. const children = [];
  14989. for ( const property of Object.getOwnPropertyNames( this ) ) {
  14990. if ( property.startsWith( '_' ) === true ) continue;
  14991. const object = this[ property ];
  14992. if ( object && object.isNode === true ) {
  14993. children.push( { property, childNode: object } );
  14994. }
  14995. }
  14996. return children;
  14997. }
  14998. /**
  14999. * Allows to define a custom cache key that influence the material key computation
  15000. * for render objects.
  15001. *
  15002. * @return {string} The custom cache key.
  15003. */
  15004. customProgramCacheKey() {
  15005. const values = [];
  15006. for ( const { property, childNode } of this._getNodeChildren() ) {
  15007. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey() );
  15008. }
  15009. return this.type + hashArray( values );
  15010. }
  15011. /**
  15012. * Builds this material with the given node builder.
  15013. *
  15014. * @param {NodeBuilder} builder - The current node builder.
  15015. */
  15016. build( builder ) {
  15017. this.setup( builder );
  15018. }
  15019. /**
  15020. * Setups a node material observer with the given builder.
  15021. *
  15022. * @param {NodeBuilder} builder - The current node builder.
  15023. * @return {NodeMaterialObserver} The node material observer.
  15024. */
  15025. setupObserver( builder ) {
  15026. return new NodeMaterialObserver( builder );
  15027. }
  15028. /**
  15029. * Setups the vertex and fragment stage of this node material.
  15030. *
  15031. * @param {NodeBuilder} builder - The current node builder.
  15032. */
  15033. setup( builder ) {
  15034. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  15035. builder.context.setupPositionView = () => this.setupPositionView( builder );
  15036. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  15037. const renderer = builder.renderer;
  15038. const renderTarget = renderer.getRenderTarget();
  15039. // < VERTEX STAGE >
  15040. builder.addStack();
  15041. const mvp = this.setupVertex( builder );
  15042. const vertexNode = subBuild( this.vertexNode || mvp, 'VERTEX' );
  15043. builder.context.clipSpace = vertexNode;
  15044. builder.stack.outputNode = vertexNode;
  15045. this.setupHardwareClipping( builder );
  15046. if ( this.geometryNode !== null ) {
  15047. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  15048. }
  15049. builder.addFlow( 'vertex', builder.removeStack() );
  15050. // < FRAGMENT STAGE >
  15051. builder.addStack();
  15052. let resultNode;
  15053. const clippingNode = this.setupClipping( builder );
  15054. if ( this.depthWrite === true || this.depthTest === true ) {
  15055. // only write depth if depth buffer is configured
  15056. if ( renderTarget !== null ) {
  15057. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  15058. } else {
  15059. if ( renderer.depth === true ) this.setupDepth( builder );
  15060. }
  15061. }
  15062. if ( this.fragmentNode === null ) {
  15063. this.setupDiffuseColor( builder );
  15064. this.setupAmbientOcclusion( builder );
  15065. this.setupVariants( builder );
  15066. const outgoingLightNode = this.setupLighting( builder );
  15067. if ( clippingNode !== null ) builder.stack.addToStack( clippingNode );
  15068. // force unsigned floats - useful for RenderTargets
  15069. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  15070. resultNode = this.setupOutput( builder, basicOutput );
  15071. // OUTPUT NODE
  15072. output.assign( resultNode );
  15073. //
  15074. const isCustomOutput = this.outputNode !== null;
  15075. if ( isCustomOutput ) resultNode = this.outputNode;
  15076. //
  15077. if ( builder.context.getOutput ) {
  15078. resultNode = builder.context.getOutput( resultNode, builder );
  15079. }
  15080. // MRT
  15081. if ( renderTarget !== null ) {
  15082. const mrt = renderer.getMRT();
  15083. const materialMRT = this.mrtNode;
  15084. if ( mrt !== null ) {
  15085. if ( isCustomOutput ) output.assign( resultNode );
  15086. resultNode = mrt;
  15087. if ( materialMRT !== null ) {
  15088. resultNode = mrt.merge( materialMRT );
  15089. }
  15090. } else if ( materialMRT !== null ) {
  15091. resultNode = materialMRT;
  15092. }
  15093. }
  15094. } else {
  15095. let fragmentNode = this.fragmentNode;
  15096. if ( fragmentNode.isOutputStructNode !== true ) {
  15097. fragmentNode = fragmentNode.convert( builder.getOutputType() );
  15098. }
  15099. resultNode = this.setupOutput( builder, fragmentNode );
  15100. }
  15101. builder.stack.outputNode = resultNode;
  15102. builder.addFlow( 'fragment', builder.removeStack() );
  15103. // < OBSERVER >
  15104. builder.observer = this.setupObserver( builder );
  15105. }
  15106. /**
  15107. * Setups the clipping node.
  15108. *
  15109. * @param {NodeBuilder} builder - The current node builder.
  15110. * @return {ClippingNode} The clipping node.
  15111. */
  15112. setupClipping( builder ) {
  15113. if ( builder.clippingContext === null ) return null;
  15114. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  15115. let result = null;
  15116. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  15117. const samples = builder.renderer.currentSamples;
  15118. if ( this.alphaToCoverage && samples > 1 ) {
  15119. // to be added to flow when the color/alpha value has been determined
  15120. result = clippingAlpha();
  15121. } else {
  15122. builder.stack.addToStack( clipping() );
  15123. }
  15124. }
  15125. return result;
  15126. }
  15127. /**
  15128. * Setups the hardware clipping if available on the current device.
  15129. *
  15130. * @param {NodeBuilder} builder - The current node builder.
  15131. */
  15132. setupHardwareClipping( builder ) {
  15133. builder.hardwareClipping = false;
  15134. if ( builder.clippingContext === null ) return;
  15135. const candidateCount = builder.clippingContext.unionPlanes.length;
  15136. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  15137. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  15138. builder.stack.addToStack( hardwareClipping() );
  15139. builder.hardwareClipping = true;
  15140. }
  15141. return;
  15142. }
  15143. /**
  15144. * Setups the depth of this material.
  15145. *
  15146. * @param {NodeBuilder} builder - The current node builder.
  15147. */
  15148. setupDepth( builder ) {
  15149. const { renderer, camera } = builder;
  15150. // Depth
  15151. let depthNode = this.depthNode;
  15152. if ( depthNode === null ) {
  15153. const mrt = renderer.getMRT();
  15154. if ( mrt && mrt.has( 'depth' ) ) {
  15155. depthNode = mrt.get( 'depth' );
  15156. } else if ( renderer.logarithmicDepthBuffer === true ) {
  15157. if ( camera.isPerspectiveCamera ) {
  15158. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  15159. } else {
  15160. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  15161. }
  15162. }
  15163. }
  15164. if ( depthNode !== null ) {
  15165. depth.assign( depthNode ).toStack();
  15166. }
  15167. }
  15168. /**
  15169. * Setups the position node in view space. This method exists
  15170. * so derived node materials can modify the implementation e.g. sprite materials.
  15171. *
  15172. * @param {NodeBuilder} builder - The current node builder.
  15173. * @return {Node<vec3>} The position in view space.
  15174. */
  15175. setupPositionView( /*builder*/ ) {
  15176. return modelViewMatrix.mul( positionLocal ).xyz;
  15177. }
  15178. /**
  15179. * Setups the position in clip space.
  15180. *
  15181. * @param {NodeBuilder} builder - The current node builder.
  15182. * @return {Node<vec4>} The position in view space.
  15183. */
  15184. setupModelViewProjection( /*builder*/ ) {
  15185. return cameraProjectionMatrix.mul( positionView );
  15186. }
  15187. /**
  15188. * Setups the logic for the vertex stage.
  15189. *
  15190. * @param {NodeBuilder} builder - The current node builder.
  15191. * @return {Node<vec4>} The position in clip space.
  15192. */
  15193. setupVertex( builder ) {
  15194. builder.addStack();
  15195. this.setupPosition( builder );
  15196. builder.context.position = builder.removeStack();
  15197. return modelViewProjection;
  15198. }
  15199. /**
  15200. * Setups the computation of the position in local space.
  15201. *
  15202. * @param {NodeBuilder} builder - The current node builder.
  15203. * @return {Node<vec3>} The position in local space.
  15204. */
  15205. setupPosition( builder ) {
  15206. const { object, geometry } = builder;
  15207. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  15208. morphReference( object );
  15209. }
  15210. if ( object.isSkinnedMesh === true ) {
  15211. skinning( object );
  15212. }
  15213. if ( this.displacementMap ) {
  15214. const displacementMap = materialReference( 'displacementMap', 'texture' );
  15215. const displacementScale = materialReference( 'displacementScale', 'float' );
  15216. const displacementBias = materialReference( 'displacementBias', 'float' );
  15217. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  15218. }
  15219. if ( object.isBatchedMesh ) {
  15220. batch( object );
  15221. }
  15222. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  15223. instancedMesh( object );
  15224. }
  15225. if ( this.positionNode !== null ) {
  15226. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  15227. }
  15228. return positionLocal;
  15229. }
  15230. /**
  15231. * Setups the computation of the material's diffuse color.
  15232. *
  15233. * @param {NodeBuilder} builder - The current node builder.
  15234. * @param {BufferGeometry} geometry - The geometry.
  15235. */
  15236. setupDiffuseColor( builder ) {
  15237. const { object, geometry } = builder;
  15238. // MASK
  15239. if ( this.maskNode !== null ) {
  15240. // Discard if the mask is `false`
  15241. bool( this.maskNode ).not().discard();
  15242. }
  15243. // COLOR
  15244. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  15245. // VERTEX COLORS
  15246. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  15247. colorNode = colorNode.mul( vertexColor() );
  15248. }
  15249. // INSTANCED COLORS
  15250. if ( object.instanceColor ) {
  15251. colorNode = instanceColor.mul( colorNode );
  15252. }
  15253. if ( object.isBatchedMesh && object._colorsTexture ) {
  15254. colorNode = batchColor.mul( colorNode );
  15255. }
  15256. // DIFFUSE COLOR
  15257. diffuseColor.assign( colorNode );
  15258. // OPACITY
  15259. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15260. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  15261. // ALPHA TEST
  15262. let alphaTestNode = null;
  15263. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  15264. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  15265. if ( this.alphaToCoverage === true ) {
  15266. diffuseColor.a = smoothstep( alphaTestNode, alphaTestNode.add( fwidth( diffuseColor.a ) ), diffuseColor.a );
  15267. diffuseColor.a.lessThanEqual( 0 ).discard();
  15268. } else {
  15269. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  15270. }
  15271. }
  15272. // ALPHA HASH
  15273. if ( this.alphaHash === true ) {
  15274. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  15275. }
  15276. // OPAQUE
  15277. if ( builder.isOpaque() ) {
  15278. diffuseColor.a.assign( 1.0 );
  15279. }
  15280. }
  15281. /**
  15282. * Abstract interface method that can be implemented by derived materials
  15283. * to setup material-specific node variables.
  15284. *
  15285. * @abstract
  15286. * @param {NodeBuilder} builder - The current node builder.
  15287. */
  15288. setupVariants( /*builder*/ ) {
  15289. // Interface function.
  15290. }
  15291. /**
  15292. * Setups the outgoing light node variable
  15293. *
  15294. * @return {Node<vec3>} The outgoing light node.
  15295. */
  15296. setupOutgoingLight() {
  15297. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  15298. }
  15299. /**
  15300. * Setups the normal node from the material.
  15301. *
  15302. * @return {Node<vec3>} The normal node.
  15303. */
  15304. setupNormal() {
  15305. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  15306. }
  15307. /**
  15308. * Setups the environment node from the material.
  15309. *
  15310. * @param {NodeBuilder} builder - The current node builder.
  15311. * @return {Node<vec4>} The environment node.
  15312. */
  15313. setupEnvironment( /*builder*/ ) {
  15314. let node = null;
  15315. if ( this.envNode ) {
  15316. node = this.envNode;
  15317. } else if ( this.envMap ) {
  15318. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  15319. }
  15320. return node;
  15321. }
  15322. /**
  15323. * Setups the light map node from the material.
  15324. *
  15325. * @param {NodeBuilder} builder - The current node builder.
  15326. * @return {Node<vec3>} The light map node.
  15327. */
  15328. setupLightMap( builder ) {
  15329. let node = null;
  15330. if ( builder.material.lightMap ) {
  15331. node = new IrradianceNode( materialLightMap );
  15332. }
  15333. return node;
  15334. }
  15335. /**
  15336. * Setups the lights node based on the scene, environment and material.
  15337. *
  15338. * @param {NodeBuilder} builder - The current node builder.
  15339. * @return {LightingNode<Array>} The lights node.
  15340. */
  15341. setupMaterialLightings( builder ) {
  15342. const materialLightsNode = [];
  15343. if ( builder.renderer.lighting.enabled === false ) {
  15344. return materialLightsNode;
  15345. }
  15346. //
  15347. const envNode = this.setupEnvironment( builder );
  15348. if ( envNode && envNode.isLightingNode ) {
  15349. materialLightsNode.push( envNode );
  15350. }
  15351. const lightMapNode = this.setupLightMap( builder );
  15352. if ( lightMapNode && lightMapNode.isLightingNode ) {
  15353. materialLightsNode.push( lightMapNode );
  15354. }
  15355. if ( builder.context.ambientOcclusion ) {
  15356. materialLightsNode.push( new AONode( builder.context.ambientOcclusion ) );
  15357. }
  15358. return materialLightsNode;
  15359. }
  15360. /**
  15361. * Setups the ambient occlusion node from the material.
  15362. *
  15363. * @param {NodeBuilder} builder - The current node builder.
  15364. * @return {Node} The ambient occlusion node.
  15365. */
  15366. setupAmbientOcclusion( builder ) {
  15367. let aoNode = this.aoNode;
  15368. if ( aoNode === null && builder.material.aoMap ) {
  15369. aoNode = materialAO;
  15370. }
  15371. if ( builder.context.getAO ) {
  15372. aoNode = builder.context.getAO( aoNode, builder );
  15373. }
  15374. if ( aoNode !== null ) {
  15375. ambientOcclusion.assign( aoNode );
  15376. builder.context.ambientOcclusion = ambientOcclusion;
  15377. }
  15378. }
  15379. /**
  15380. * This method should be implemented by most derived materials
  15381. * since it defines the material's lighting model.
  15382. *
  15383. * @abstract
  15384. * @param {NodeBuilder} builder - The current node builder.
  15385. * @return {LightingModel} The lighting model.
  15386. */
  15387. setupLightingModel( /*builder*/ ) {
  15388. // Interface function.
  15389. }
  15390. /**
  15391. * Setups the outgoing light node.
  15392. *
  15393. * @param {NodeBuilder} builder - The current node builder.
  15394. * @return {Node<vec3>} The outgoing light node.
  15395. */
  15396. setupLighting( builder ) {
  15397. const { material } = builder;
  15398. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  15399. // OUTGOING LIGHT
  15400. const lights = this.lights === true || this.lightsNode !== null;
  15401. const materialLightings = this.lights === true ? this.setupMaterialLightings( builder ) : [];
  15402. const lightsNode = lights ? ( this.lightsNode || builder.lightsNode ) : null;
  15403. let outgoingLightNode = this.setupOutgoingLight( builder );
  15404. if ( lightsNode && ( materialLightings.length > 0 || lightsNode.getScope().hasLights ) ) {
  15405. const lightingModel = this.setupLightingModel( builder ) || null;
  15406. outgoingLightNode = lightingContext( lightsNode, lightingModel, materialLightings, backdropNode, backdropAlphaNode );
  15407. } else if ( backdropNode !== null ) {
  15408. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  15409. }
  15410. // EMISSIVE
  15411. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  15412. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  15413. outgoingLightNode = outgoingLightNode.add( emissive );
  15414. }
  15415. return outgoingLightNode;
  15416. }
  15417. /**
  15418. * Setup the fog.
  15419. *
  15420. * @param {NodeBuilder} builder - The current node builder.
  15421. * @param {Node<vec4>} outputNode - The existing output node.
  15422. * @return {Node<vec4>} The output node.
  15423. */
  15424. setupFog( builder, outputNode ) {
  15425. const fogNode = builder.fogNode;
  15426. if ( fogNode ) {
  15427. output.assign( outputNode );
  15428. outputNode = vec4( fogNode.toVar() );
  15429. }
  15430. return outputNode;
  15431. }
  15432. /**
  15433. * Setups premultiplied alpha.
  15434. *
  15435. * @param {NodeBuilder} builder - The current node builder.
  15436. * @param {Node<vec4>} outputNode - The existing output node.
  15437. * @return {Node<vec4>} The output node.
  15438. */
  15439. setupPremultipliedAlpha( builder, outputNode ) {
  15440. return premultiplyAlpha( outputNode );
  15441. }
  15442. /**
  15443. * Setups the output node.
  15444. *
  15445. * This method can be implemented by derived materials to extend the functionality
  15446. * of the material's output or replace it altogether.
  15447. *
  15448. * ```js
  15449. * class ColoredShadowMaterial extends MeshPhongNodeMaterial {
  15450. * constructor( parameters ) {
  15451. * super( parameters );
  15452. * this._shadeColor = uniform( new Color( parameters.shadeColor ?? 0xff0000 ) );
  15453. * }
  15454. *
  15455. * setupOutput( builder, outputNode ) {
  15456. * // Modify the native output of the MeshPhongNodeMaterial fragment shader
  15457. * const brightness = min( outputNode.r, 1.0 );
  15458. * const mixedColor = mix( this._shadeColor, diffuseColor.rgb, brightness );
  15459. * // Return new output back into NodeMaterial flow
  15460. * return super.setupOutput( builder, vec4( mixedColor, outputNode.a ) );
  15461. * }
  15462. * }
  15463. * ```
  15464. *
  15465. * @param {NodeBuilder} builder - The current node builder.
  15466. * @param {Node<vec4>} outputNode - The existing output node.
  15467. * @return {Node<vec4>} The output node.
  15468. */
  15469. setupOutput( builder, outputNode ) {
  15470. // FOG
  15471. if ( this.fog === true ) {
  15472. outputNode = this.setupFog( builder, outputNode );
  15473. }
  15474. // PREMULTIPLIED ALPHA
  15475. if ( this.premultipliedAlpha === true ) {
  15476. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  15477. }
  15478. return outputNode;
  15479. }
  15480. /**
  15481. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  15482. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  15483. * defining all material properties of the classic type in the node type.
  15484. *
  15485. * @param {Material} material - The material to copy properties with their values to this node material.
  15486. */
  15487. setDefaultValues( material ) {
  15488. // This approach is to reuse the native refreshUniforms*
  15489. // and turn available the use of features like transmission and environment in core
  15490. for ( const property in material ) {
  15491. const value = material[ property ];
  15492. if ( this[ property ] === undefined ) {
  15493. this[ property ] = value;
  15494. if ( value && value.clone ) this[ property ] = value.clone();
  15495. }
  15496. }
  15497. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  15498. for ( const key in descriptors ) {
  15499. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined && descriptors[ key ].get !== undefined ) {
  15500. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  15501. }
  15502. }
  15503. }
  15504. /**
  15505. * Serializes this material to JSON.
  15506. *
  15507. * @param {?(Object|string)} meta - The meta information for serialization.
  15508. * @return {Object} The serialized node.
  15509. */
  15510. toJSON( meta ) {
  15511. const isRoot = ( meta === undefined || typeof meta === 'string' );
  15512. if ( isRoot ) {
  15513. meta = {
  15514. textures: {},
  15515. images: {},
  15516. nodes: {}
  15517. };
  15518. }
  15519. const data = Material.prototype.toJSON.call( this, meta );
  15520. data.inputNodes = {};
  15521. for ( const { property, childNode } of this._getNodeChildren() ) {
  15522. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  15523. }
  15524. // TODO: Copied from Object3D.toJSON
  15525. function extractFromCache( cache ) {
  15526. const values = [];
  15527. for ( const key in cache ) {
  15528. const data = cache[ key ];
  15529. delete data.metadata;
  15530. values.push( data );
  15531. }
  15532. return values;
  15533. }
  15534. if ( isRoot ) {
  15535. const textures = extractFromCache( meta.textures );
  15536. const images = extractFromCache( meta.images );
  15537. const nodes = extractFromCache( meta.nodes );
  15538. if ( textures.length > 0 ) data.textures = textures;
  15539. if ( images.length > 0 ) data.images = images;
  15540. if ( nodes.length > 0 ) data.nodes = nodes;
  15541. }
  15542. return data;
  15543. }
  15544. /**
  15545. * Copies the common properties of the given material to this instance.
  15546. *
  15547. * @param {Material} source - The material to copy.
  15548. * @return {NodeMaterial} A reference to this node material.
  15549. */
  15550. copy( source ) {
  15551. const descriptors = Object.getOwnPropertyDescriptors( this.constructor.prototype );
  15552. for ( const property in descriptors ) {
  15553. if ( descriptors[ property ].set !== undefined && source[ property ] !== undefined ) {
  15554. const value = source[ property ];
  15555. if ( this[ property ] && this[ property ].copy !== undefined ) {
  15556. this[ property ].copy( value );
  15557. } else {
  15558. this[ property ] = value;
  15559. }
  15560. }
  15561. }
  15562. for ( const property in this ) {
  15563. // Skip internal/private properties (starting with '_'), flags (starting with 'is' + uppercase),
  15564. // and properties that are handled separately or should not be copied (id, uuid, version, type, userData, clippingPlanes).
  15565. if ( /^(?:is[A-Z]|_)|^(?:id|uuid|version|type|userData|clippingPlanes)$/.test( property ) ) continue;
  15566. if ( this[ property ] !== undefined && source[ property ] !== undefined ) {
  15567. const value = source[ property ];
  15568. if ( this[ property ] && this[ property ].copy !== undefined ) {
  15569. this[ property ].copy( value );
  15570. } else {
  15571. this[ property ] = value;
  15572. }
  15573. }
  15574. }
  15575. this.clippingPlanes = source.clippingPlanes ? source.clippingPlanes.map( ( plane ) => plane.clone() ) : null;
  15576. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  15577. return this;
  15578. }
  15579. }
  15580. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  15581. /**
  15582. * Node material version of {@link LineBasicMaterial}.
  15583. *
  15584. * @augments NodeMaterial
  15585. */
  15586. class LineBasicNodeMaterial extends NodeMaterial {
  15587. static get type() {
  15588. return 'LineBasicNodeMaterial';
  15589. }
  15590. /**
  15591. * Constructs a new line basic node material.
  15592. *
  15593. * @param {Object} [parameters] - The configuration parameter.
  15594. */
  15595. constructor( parameters ) {
  15596. super();
  15597. /**
  15598. * This flag can be used for type testing.
  15599. *
  15600. * @type {boolean}
  15601. * @readonly
  15602. * @default true
  15603. */
  15604. this.isLineBasicNodeMaterial = true;
  15605. this.setDefaultValues( _defaultValues$d );
  15606. this.setValues( parameters );
  15607. }
  15608. }
  15609. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  15610. /**
  15611. * Node material version of {@link LineDashedMaterial}.
  15612. *
  15613. * @augments NodeMaterial
  15614. */
  15615. class LineDashedNodeMaterial extends NodeMaterial {
  15616. static get type() {
  15617. return 'LineDashedNodeMaterial';
  15618. }
  15619. /**
  15620. * Constructs a new line dashed node material.
  15621. *
  15622. * @param {Object} [parameters] - The configuration parameter.
  15623. */
  15624. constructor( parameters ) {
  15625. super();
  15626. /**
  15627. * This flag can be used for type testing.
  15628. *
  15629. * @type {boolean}
  15630. * @readonly
  15631. * @default true
  15632. */
  15633. this.isLineDashedNodeMaterial = true;
  15634. this.setDefaultValues( _defaultValues$c );
  15635. /**
  15636. * The dash offset.
  15637. *
  15638. * @type {number}
  15639. * @default 0
  15640. */
  15641. this.dashOffset = 0;
  15642. /**
  15643. * The offset of dash materials is by default inferred from the `dashOffset`
  15644. * property. This node property allows to overwrite the default
  15645. * and define the offset with a node instead.
  15646. *
  15647. * If you don't want to overwrite the offset but modify the existing
  15648. * value instead, use {@link materialLineDashOffset}.
  15649. *
  15650. * @type {?Node<float>}
  15651. * @default null
  15652. */
  15653. this.offsetNode = null;
  15654. /**
  15655. * The scale of dash materials is by default inferred from the `scale`
  15656. * property. This node property allows to overwrite the default
  15657. * and define the scale with a node instead.
  15658. *
  15659. * If you don't want to overwrite the scale but modify the existing
  15660. * value instead, use {@link materialLineScale}.
  15661. *
  15662. * @type {?Node<float>}
  15663. * @default null
  15664. */
  15665. this.dashScaleNode = null;
  15666. /**
  15667. * The dash size of dash materials is by default inferred from the `dashSize`
  15668. * property. This node property allows to overwrite the default
  15669. * and define the dash size with a node instead.
  15670. *
  15671. * If you don't want to overwrite the dash size but modify the existing
  15672. * value instead, use {@link materialLineDashSize}.
  15673. *
  15674. * @type {?Node<float>}
  15675. * @default null
  15676. */
  15677. this.dashSizeNode = null;
  15678. /**
  15679. * The gap size of dash materials is by default inferred from the `gapSize`
  15680. * property. This node property allows to overwrite the default
  15681. * and define the gap size with a node instead.
  15682. *
  15683. * If you don't want to overwrite the gap size but modify the existing
  15684. * value instead, use {@link materialLineGapSize}.
  15685. *
  15686. * @type {?Node<float>}
  15687. * @default null
  15688. */
  15689. this.gapSizeNode = null;
  15690. this.setValues( parameters );
  15691. }
  15692. /**
  15693. * Setups the dash specific node variables.
  15694. *
  15695. * @param {NodeBuilder} builder - The current node builder.
  15696. */
  15697. setupVariants( /* builder */ ) {
  15698. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15699. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15700. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15701. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15702. dashSize.assign( dashSizeNode );
  15703. gapSize.assign( gapSizeNode );
  15704. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  15705. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  15706. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  15707. }
  15708. }
  15709. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  15710. /**
  15711. * Varying node representing the world position of the segment start in view space.
  15712. * Used for distance and coordinate calculations across the fragment shader.
  15713. * @type {VaryingNode<vec3>}
  15714. */
  15715. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  15716. /**
  15717. * Varying node representing the world position of the segment end in view space.
  15718. * Used for distance and coordinate calculations across the fragment shader.
  15719. * @type {VaryingNode<vec3>}
  15720. */
  15721. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  15722. /**
  15723. * Varying node representing the accumulated distance along the line.
  15724. * Crucial for correctly computing dashed line intervals in fragment stage.
  15725. * @type {VaryingNode<float>}
  15726. */
  15727. const lineDistance = varyingProperty( 'float', 'lineDistance' );
  15728. /**
  15729. * Varying node representing the interpolated world/view position of the current fragment.
  15730. * Used for line/ray distance checks under perspective projection.
  15731. * @type {VaryingNode<vec4>}
  15732. */
  15733. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  15734. /**
  15735. * Trims the line segment to avoid rendering behind the camera near plane.
  15736. * Computes an interpolation factor (alpha) to clamp the segment's coordinate.
  15737. *
  15738. * @param {Object} inputs
  15739. * @param {Node<vec4>} inputs.start - Segment start position in view space.
  15740. * @param {Node<vec4>} inputs.end - Segment end position in view space.
  15741. * @returns {Node<float>} The interpolation factor (alpha) to trim the segment.
  15742. */
  15743. const trimSegmentAlpha = Fn( ( { start, end } ) => {
  15744. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  15745. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  15746. // we need different nearEstimate formula for reversed and default depth buffer
  15747. // a is positive with a reversed depth buffer so it can be used for controlling the code flow
  15748. const nearEstimate = a.greaterThan( 0 ).select( b.negate().div( a.add( 1 ) ), b.mul( -0.5 ).div( a ) );
  15749. return nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  15750. }, { start: 'vec4', end: 'vec4', return: 'float' } );
  15751. /**
  15752. * Calculates the closest points on two 3D lines.
  15753. * Used for perspective-correct line rendering and coordinates interpolation.
  15754. *
  15755. * @param {Object} inputs
  15756. * @param {Node<vec3>} inputs.p1 - Start of line 1.
  15757. * @param {Node<vec3>} inputs.p2 - End of line 1.
  15758. * @param {Node<vec3>} inputs.p3 - Start of line 2.
  15759. * @param {Node<vec3>} inputs.p4 - End of line 2.
  15760. * @returns {Node<vec2>} A vec2 containing the parametric coordinates (mua, mub) of the closest points on line 1 and line 2.
  15761. */
  15762. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  15763. const p13 = p1.sub( p3 );
  15764. const p43 = p4.sub( p3 );
  15765. const p21 = p2.sub( p1 );
  15766. const d1343 = p13.dot( p43 );
  15767. const d4321 = p43.dot( p21 );
  15768. const d1321 = p13.dot( p21 );
  15769. const d4343 = p43.dot( p43 );
  15770. const d2121 = p21.dot( p21 );
  15771. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  15772. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  15773. const mua = numer.div( denom ).clamp();
  15774. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  15775. return vec2( mua, mub );
  15776. }, { p1: 'vec3', p2: 'vec3', p3: 'vec3', p4: 'vec3', return: 'vec2' } );
  15777. /**
  15778. * TSL node acting as a custom Model-View-Projection (MVP) for fat lines,
  15779. * expanding 3D segments into screen/world-facing ribbons of a specified width.
  15780. *
  15781. * @tsl
  15782. * @type {Node<vec4>}
  15783. */
  15784. const mvpLine = Fn( ( { material } ) => {
  15785. const useDash = material._useDash;
  15786. const useWorldUnits = material._useWorldUnits;
  15787. const instanceStart = attribute( 'instanceStart' );
  15788. const instanceEnd = attribute( 'instanceEnd' );
  15789. // camera space
  15790. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  15791. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  15792. let distanceStart, distanceEnd;
  15793. if ( useDash ) {
  15794. distanceStart = float( attribute( 'instanceDistanceStart' ) ).toVar( 'distanceStart' );
  15795. distanceEnd = float( attribute( 'instanceDistanceEnd' ) ).toVar( 'distanceEnd' );
  15796. }
  15797. if ( useWorldUnits ) {
  15798. worldStart.assign( start.xyz );
  15799. worldEnd.assign( end.xyz );
  15800. }
  15801. const aspect = viewport.z.div( viewport.w );
  15802. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  15803. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  15804. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  15805. // perhaps there is a more elegant solution -- WestLangley
  15806. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  15807. If( perspective, () => {
  15808. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  15809. const alpha = trimSegmentAlpha( { start, end } );
  15810. end.assign( vec4( mix( start.xyz, end.xyz, alpha ), end.w ) );
  15811. if ( useDash ) {
  15812. distanceEnd.assign( mix( distanceStart, distanceEnd, alpha ) );
  15813. }
  15814. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  15815. const alpha = trimSegmentAlpha( { start: end, end: start } );
  15816. start.assign( vec4( mix( end.xyz, start.xyz, alpha ), start.w ) );
  15817. if ( useDash ) {
  15818. distanceStart.assign( mix( distanceEnd, distanceStart, alpha ) );
  15819. }
  15820. } );
  15821. } );
  15822. if ( useDash ) {
  15823. const dashScaleNode = material.dashScaleNode ? float( material.dashScaleNode ) : materialLineScale;
  15824. const offsetNode = material.offsetNode ? float( material.offsetNode ) : materialLineDashOffset;
  15825. let lineDist = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( distanceStart ), dashScaleNode.mul( distanceEnd ) );
  15826. lineDist = lineDist.add( offsetNode );
  15827. lineDistance.assign( lineDist );
  15828. }
  15829. // clip space
  15830. const clipStart = cameraProjectionMatrix.mul( start );
  15831. const clipEnd = cameraProjectionMatrix.mul( end );
  15832. // ndc space
  15833. const ndcStart = clipStart.xyz.div( clipStart.w );
  15834. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  15835. // direction
  15836. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  15837. // account for clip-space aspect ratio
  15838. dir.x.assign( dir.x.mul( aspect ) );
  15839. dir.assign( dir.normalize() );
  15840. const clip = vec4().toVar();
  15841. if ( useWorldUnits ) {
  15842. // get the offset direction as perpendicular to the view vector
  15843. const worldDir = end.xyz.sub( start.xyz ).normalize();
  15844. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  15845. const worldUp = worldDir.cross( tmpFwd ).normalize();
  15846. const worldFwd = worldDir.cross( worldUp );
  15847. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  15848. // height offset
  15849. const hw = materialLineWidth.mul( 0.5 );
  15850. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  15851. // don't extend the line if we're rendering dashes because we
  15852. // won't be rendering the endcaps
  15853. if ( ! useDash ) {
  15854. // cap extension
  15855. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  15856. // add width to the box
  15857. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  15858. // endcaps
  15859. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  15860. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  15861. } );
  15862. }
  15863. // project the worldpos
  15864. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  15865. // shift the depth of the projected points so the line
  15866. // segments overlap neatly
  15867. const clipPose = vec3().toVar();
  15868. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  15869. clip.z.assign( clipPose.z.mul( clip.w ) );
  15870. } else {
  15871. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  15872. // undo aspect ratio adjustment
  15873. dir.x.assign( dir.x.div( aspect ) );
  15874. offset.x.assign( offset.x.div( aspect ) );
  15875. // sign flip
  15876. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  15877. // endcaps
  15878. If( positionGeometry.y.lessThan( 0.0 ), () => {
  15879. offset.assign( offset.sub( dir ) );
  15880. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  15881. offset.assign( offset.add( dir ) );
  15882. } );
  15883. // adjust for linewidth
  15884. offset.assign( offset.mul( materialLineWidth ) );
  15885. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  15886. offset.assign( offset.div( viewport.w.div( screenDPR ) ) );
  15887. // select end
  15888. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  15889. // back to clip space
  15890. offset.assign( offset.mul( clip.w ) );
  15891. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  15892. }
  15893. return clip;
  15894. } )();
  15895. /**
  15896. * TSL fragment node that computes the shape/coverage (alpha) of the fat line segment.
  15897. * Handles dash/gap generation, alpha-to-coverage rendering, and round endcaps.
  15898. *
  15899. * @tsl
  15900. * @type {Node<float>}
  15901. */
  15902. const alphaLine = Fn( ( { material, renderer } ) => {
  15903. const useAlphaToCoverage = material._useAlphaToCoverage;
  15904. const useDash = material._useDash;
  15905. const useWorldUnits = material._useWorldUnits;
  15906. const vUv = uv$1();
  15907. if ( useDash ) {
  15908. const dashSizeNode = material.dashSizeNode ? float( material.dashSizeNode ) : materialLineDashSize;
  15909. const gapSizeNode = material.gapSizeNode ? float( material.gapSizeNode ) : materialLineGapSize;
  15910. dashSize.assign( dashSizeNode );
  15911. gapSize.assign( gapSizeNode );
  15912. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  15913. lineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  15914. }
  15915. const alpha = float( 1 ).toVar( 'alpha' );
  15916. if ( useWorldUnits ) {
  15917. // Find the closest points on the view ray and the line segment
  15918. const rayEnd = worldPos.xyz.normalize().mul( 1e5 );
  15919. const lineDir = worldEnd.sub( worldStart );
  15920. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  15921. const p1 = worldStart.add( lineDir.mul( params.x ) );
  15922. const p2 = rayEnd.mul( params.y );
  15923. const delta = p1.sub( p2 );
  15924. const len = delta.length();
  15925. const norm = len.div( materialLineWidth );
  15926. if ( ! useDash ) {
  15927. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15928. const dnorm = norm.fwidth();
  15929. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  15930. } else {
  15931. norm.greaterThan( 0.5 ).discard();
  15932. }
  15933. }
  15934. } else {
  15935. // round endcaps
  15936. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15937. const a = vUv.x;
  15938. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15939. const len2 = a.mul( a ).add( b.mul( b ) );
  15940. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  15941. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15942. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  15943. } );
  15944. } else {
  15945. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15946. const a = vUv.x;
  15947. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15948. const len2 = a.mul( a ).add( b.mul( b ) );
  15949. len2.greaterThan( 1.0 ).discard();
  15950. } );
  15951. }
  15952. }
  15953. return alpha;
  15954. } )();
  15955. /**
  15956. * This node material can be used to render lines with a size larger than one
  15957. * by representing them as instanced meshes.
  15958. *
  15959. * @augments NodeMaterial
  15960. */
  15961. class Line2NodeMaterial extends NodeMaterial {
  15962. static get type() {
  15963. return 'Line2NodeMaterial';
  15964. }
  15965. /**
  15966. * Constructs a new node material for wide line rendering.
  15967. *
  15968. * @param {Object} [parameters={}] - The configuration parameter.
  15969. */
  15970. constructor( parameters = {} ) {
  15971. super();
  15972. /**
  15973. * This flag can be used for type testing.
  15974. *
  15975. * @type {boolean}
  15976. * @readonly
  15977. * @default true
  15978. */
  15979. this.isLine2NodeMaterial = true;
  15980. this.setDefaultValues( _defaultValues$b );
  15981. /**
  15982. * Whether vertex colors should be used or not.
  15983. *
  15984. * @type {boolean}
  15985. * @default false
  15986. */
  15987. this.vertexColors = parameters.vertexColors;
  15988. /**
  15989. * The dash offset.
  15990. *
  15991. * @type {number}
  15992. * @default 0
  15993. */
  15994. this.dashOffset = 0;
  15995. /**
  15996. * Defines the offset.
  15997. *
  15998. * @type {?Node<float>}
  15999. * @default null
  16000. */
  16001. this.offsetNode = null;
  16002. /**
  16003. * Defines the dash scale.
  16004. *
  16005. * @type {?Node<float>}
  16006. * @default null
  16007. */
  16008. this.dashScaleNode = null;
  16009. /**
  16010. * Defines the dash size.
  16011. *
  16012. * @type {?Node<float>}
  16013. * @default null
  16014. */
  16015. this.dashSizeNode = null;
  16016. /**
  16017. * Defines the gap size.
  16018. *
  16019. * @type {?Node<float>}
  16020. * @default null
  16021. */
  16022. this.gapSizeNode = null;
  16023. /**
  16024. * Blending is set to `NoBlending` since transparency
  16025. * is not supported, yet.
  16026. *
  16027. * @type {number}
  16028. * @default 0
  16029. */
  16030. this.blending = NoBlending;
  16031. this._useDash = parameters.dashed;
  16032. this._useAlphaToCoverage = true;
  16033. this._useWorldUnits = false;
  16034. this.setValues( parameters );
  16035. }
  16036. /**
  16037. * Setups the diffuse color of the line material in the fragment stage.
  16038. * Overrides the base setup to incorporate line/dash rendering and blending.
  16039. *
  16040. * @param {NodeBuilder} builder - The current node builder.
  16041. */
  16042. setupDiffuseColor( builder ) {
  16043. super.setupDiffuseColor( builder );
  16044. diffuseColor.a.mulAssign( alphaLine );
  16045. if ( this.vertexColors === true && builder.geometry.hasAttribute( 'instanceColorStart' ) ) {
  16046. const instanceColorStart = attribute( 'instanceColorStart' );
  16047. const instanceColorEnd = attribute( 'instanceColorEnd' );
  16048. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  16049. diffuseColor.rgb.mulAssign( instanceColor );
  16050. }
  16051. if ( this.transparent ) {
  16052. diffuseColor.rgb.assign( diffuseColor.rgb.mul( diffuseColor.a ).add( viewportOpaqueMipTexture().rgb.mul( diffuseColor.a.oneMinus() ) ) );
  16053. }
  16054. }
  16055. /**
  16056. * Setups the position in clip space for the vertex stage of the fat line.
  16057. * Overrides the default model-view-projection to return the expanded fat line vertex coordinates.
  16058. *
  16059. * @param {NodeBuilder} builder - The current node builder.
  16060. * @return {Node<vec4>} The position of the fat line vertex in clip space.
  16061. */
  16062. setupModelViewProjection( /*builder*/ ) {
  16063. return mvpLine;
  16064. }
  16065. /**
  16066. * Defines the lines color.
  16067. *
  16068. * @deprecated since r185. Use {@link NodeMaterial#colorNode} instead.
  16069. * @type {?Node<vec3>}
  16070. */
  16071. get lineColorNode() {
  16072. return this.colorNode;
  16073. }
  16074. set lineColorNode( value ) {
  16075. warnOnce( 'Line2NodeMaterial: "lineColorNode" has been deprecated. Use "colorNode" instead.' ); // @deprecated r185
  16076. this.colorNode = value;
  16077. }
  16078. /**
  16079. * Whether the lines should sized in world units or not.
  16080. * When set to `false` the unit is pixel.
  16081. *
  16082. * @type {boolean}
  16083. * @default false
  16084. */
  16085. get worldUnits() {
  16086. return this._useWorldUnits;
  16087. }
  16088. set worldUnits( value ) {
  16089. if ( this._useWorldUnits !== value ) {
  16090. this._useWorldUnits = value;
  16091. this.needsUpdate = true;
  16092. }
  16093. }
  16094. /**
  16095. * Whether the lines should be dashed or not.
  16096. *
  16097. * @type {boolean}
  16098. * @default false
  16099. */
  16100. get dashed() {
  16101. return this._useDash;
  16102. }
  16103. set dashed( value ) {
  16104. if ( this._useDash !== value ) {
  16105. this._useDash = value;
  16106. this.needsUpdate = true;
  16107. }
  16108. }
  16109. /**
  16110. * Whether alpha to coverage should be used or not.
  16111. *
  16112. * @type {boolean}
  16113. * @default true
  16114. */
  16115. get alphaToCoverage() {
  16116. return this._useAlphaToCoverage;
  16117. }
  16118. set alphaToCoverage( value ) {
  16119. if ( this._useAlphaToCoverage !== value ) {
  16120. this._useAlphaToCoverage = value;
  16121. this.needsUpdate = true;
  16122. }
  16123. }
  16124. }
  16125. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  16126. /**
  16127. * Node material version of {@link MeshNormalMaterial}.
  16128. *
  16129. * @augments NodeMaterial
  16130. */
  16131. class MeshNormalNodeMaterial extends NodeMaterial {
  16132. static get type() {
  16133. return 'MeshNormalNodeMaterial';
  16134. }
  16135. /**
  16136. * Constructs a new mesh normal node material.
  16137. *
  16138. * @param {Object} [parameters] - The configuration parameter.
  16139. */
  16140. constructor( parameters ) {
  16141. super();
  16142. /**
  16143. * This flag can be used for type testing.
  16144. *
  16145. * @type {boolean}
  16146. * @readonly
  16147. * @default true
  16148. */
  16149. this.isMeshNormalNodeMaterial = true;
  16150. this.setDefaultValues( _defaultValues$a );
  16151. this.setValues( parameters );
  16152. }
  16153. /**
  16154. * Overwrites the default implementation by computing the diffuse color
  16155. * based on the normal data.
  16156. */
  16157. setupDiffuseColor() {
  16158. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  16159. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  16160. diffuseColor.assign( colorSpaceToWorking( vec4( packNormalToRGB( normalView ), opacityNode ), SRGBColorSpace ) );
  16161. }
  16162. }
  16163. /**
  16164. * TSL function for creating an equirect uv node.
  16165. *
  16166. * Can be used to compute texture coordinates for projecting an
  16167. * equirectangular texture onto a mesh for using it as the scene's
  16168. * background.
  16169. *
  16170. * ```js
  16171. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  16172. * ```
  16173. *
  16174. * @tsl
  16175. * @function
  16176. * @param {?Node<vec3>} [direction=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  16177. * @returns {Node<vec2>}
  16178. */
  16179. const equirectUV = /*@__PURE__*/ Fn( ( [ direction = positionWorldDirection ] ) => {
  16180. const u = direction.z.atan( direction.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  16181. const v = direction.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  16182. return vec2( u, v );
  16183. } );
  16184. /**
  16185. * TSL function for creating an equirect direction node.
  16186. *
  16187. * Can be used to compute a direction vector from the given equirectangular
  16188. * UV coordinates.
  16189. *
  16190. * @tsl
  16191. * @function
  16192. * @param {?Node<vec2>} [uv=UV()] - The equirectangular UV coordinates.
  16193. * @returns {Node<vec3>} The computed direction vector.
  16194. */
  16195. const equirectDirection = /*@__PURE__*/ Fn( ( [ uv = uv$1() ] ) => {
  16196. const theta = uv.x.sub( 0.5 ).mul( Math.PI * 2 );
  16197. const phi = uv.y.sub( 0.5 ).mul( Math.PI );
  16198. const cosPhi = phi.cos();
  16199. const x = cosPhi.mul( theta.cos() );
  16200. const y = phi.sin();
  16201. const z = cosPhi.mul( theta.sin() );
  16202. return vec3( x, y, z );
  16203. } );
  16204. /**
  16205. * This class represents a cube render target. It is a special version
  16206. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  16207. *
  16208. * @augments RenderTarget
  16209. */
  16210. class CubeRenderTarget extends RenderTarget {
  16211. /**
  16212. * Constructs a new cube render target.
  16213. *
  16214. * @param {number} [size=1] - The size of the render target.
  16215. * @param {RenderTarget~Options} [options] - The configuration object.
  16216. */
  16217. constructor( size = 1, options = {} ) {
  16218. super( size, size, options );
  16219. /**
  16220. * This flag can be used for type testing.
  16221. *
  16222. * @type {boolean}
  16223. * @readonly
  16224. * @default true
  16225. */
  16226. this.isCubeRenderTarget = true;
  16227. const image = { width: size, height: size, depth: 1 };
  16228. const images = [ image, image, image, image, image, image ];
  16229. /**
  16230. * Overwritten with a different texture type.
  16231. *
  16232. * @type {DataArrayTexture}
  16233. */
  16234. this.texture = new CubeTexture( images );
  16235. this._setTextureOptions( options );
  16236. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16237. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16238. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16239. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16240. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16241. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16242. this.texture.isRenderTargetTexture = true;
  16243. }
  16244. /**
  16245. * Converts the given equirectangular texture to a cube map.
  16246. *
  16247. * @param {Renderer} renderer - The renderer.
  16248. * @param {Texture} texture - The equirectangular texture.
  16249. * @return {CubeRenderTarget} A reference to this cube render target.
  16250. */
  16251. fromEquirectangularTexture( renderer, texture$1 ) {
  16252. const currentMinFilter = texture$1.minFilter;
  16253. const currentGenerateMipmaps = texture$1.generateMipmaps;
  16254. texture$1.generateMipmaps = true;
  16255. this.texture.type = texture$1.type;
  16256. this.texture.colorSpace = texture$1.colorSpace;
  16257. this.texture.generateMipmaps = texture$1.generateMipmaps;
  16258. this.texture.minFilter = texture$1.minFilter;
  16259. this.texture.magFilter = texture$1.magFilter;
  16260. const geometry = new BoxGeometry( 5, 5, 5 );
  16261. const uvNode = equirectUV( positionWorldDirection );
  16262. const material = new NodeMaterial();
  16263. material.colorNode = texture( texture$1, uvNode, 0 );
  16264. material.side = BackSide;
  16265. material.blending = NoBlending;
  16266. const mesh = new Mesh( geometry, material );
  16267. const scene = new Scene();
  16268. scene.add( mesh );
  16269. // Avoid blurred poles
  16270. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  16271. const camera = new CubeCamera( 1, 10, this );
  16272. const currentMRT = renderer.getMRT();
  16273. renderer.setMRT( null );
  16274. camera.update( renderer, scene );
  16275. renderer.setMRT( currentMRT );
  16276. texture$1.minFilter = currentMinFilter;
  16277. texture$1.generateMipmaps = currentGenerateMipmaps;
  16278. mesh.geometry.dispose();
  16279. mesh.material.dispose();
  16280. return this;
  16281. }
  16282. /**
  16283. * Clears this cube render target.
  16284. *
  16285. * @param {Renderer} renderer - The renderer.
  16286. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16287. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16288. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16289. */
  16290. clear( renderer, color = true, depth = true, stencil = true ) {
  16291. const currentRenderTarget = renderer.getRenderTarget();
  16292. for ( let i = 0; i < 6; i ++ ) {
  16293. renderer.setRenderTarget( this, i );
  16294. renderer.clear( color, depth, stencil );
  16295. }
  16296. renderer.setRenderTarget( currentRenderTarget );
  16297. }
  16298. }
  16299. const _cache$1 = new WeakMap();
  16300. /**
  16301. * This node can be used to automatically convert environment maps in the
  16302. * equirectangular format into the cube map format.
  16303. *
  16304. * @augments TempNode
  16305. */
  16306. class CubeMapNode extends TempNode {
  16307. static get type() {
  16308. return 'CubeMapNode';
  16309. }
  16310. /**
  16311. * Constructs a new cube map node.
  16312. *
  16313. * @param {Node} envNode - The node representing the environment map.
  16314. */
  16315. constructor( envNode ) {
  16316. super( 'vec3' );
  16317. /**
  16318. * The node representing the environment map.
  16319. *
  16320. * @type {Node}
  16321. */
  16322. this.envNode = envNode;
  16323. /**
  16324. * A reference to the internal cube texture.
  16325. *
  16326. * @private
  16327. * @type {?CubeTexture}
  16328. * @default null
  16329. */
  16330. this._cubeTexture = null;
  16331. /**
  16332. * A reference to the internal cube texture node.
  16333. *
  16334. * @private
  16335. * @type {CubeTextureNode}
  16336. */
  16337. this._cubeTextureNode = cubeTexture( null );
  16338. const defaultTexture = new CubeTexture();
  16339. defaultTexture.isRenderTargetTexture = true;
  16340. /**
  16341. * A default cube texture that acts as a placeholder.
  16342. * It is used when the conversion from equirectangular to cube
  16343. * map has not finished yet for a given texture.
  16344. *
  16345. * @private
  16346. * @type {CubeTexture}
  16347. */
  16348. this._defaultTexture = defaultTexture;
  16349. /**
  16350. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  16351. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  16352. *
  16353. * @type {string}
  16354. * @default 'render'
  16355. */
  16356. this.updateBeforeType = NodeUpdateType.RENDER;
  16357. }
  16358. updateBefore( frame ) {
  16359. const { renderer, material } = frame;
  16360. const envNode = this.envNode;
  16361. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  16362. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  16363. if ( texture && texture.isTexture ) {
  16364. const mapping = texture.mapping;
  16365. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  16366. // check for converted cubemap map
  16367. if ( _cache$1.has( texture ) ) {
  16368. const cubeMap = _cache$1.get( texture );
  16369. mapTextureMapping( cubeMap, texture.mapping );
  16370. this._cubeTexture = cubeMap;
  16371. } else {
  16372. // create cube map from equirectangular map
  16373. const image = texture.image;
  16374. if ( isEquirectangularMapReady$1( image ) ) {
  16375. const renderTarget = new CubeRenderTarget( image.height );
  16376. renderTarget.fromEquirectangularTexture( renderer, texture );
  16377. mapTextureMapping( renderTarget.texture, texture.mapping );
  16378. this._cubeTexture = renderTarget.texture;
  16379. _cache$1.set( texture, renderTarget.texture );
  16380. texture.addEventListener( 'dispose', onTextureDispose );
  16381. } else {
  16382. // default cube texture as fallback when equirectangular texture is not yet loaded
  16383. this._cubeTexture = this._defaultTexture;
  16384. }
  16385. }
  16386. //
  16387. this._cubeTextureNode.value = this._cubeTexture;
  16388. } else {
  16389. // envNode already refers to a cube map
  16390. this._cubeTextureNode = this.envNode;
  16391. }
  16392. }
  16393. }
  16394. }
  16395. setup( builder ) {
  16396. this.updateBefore( builder );
  16397. return this._cubeTextureNode;
  16398. }
  16399. }
  16400. /**
  16401. * Returns true if the given equirectangular image has been fully loaded
  16402. * and is ready for further processing.
  16403. *
  16404. * @private
  16405. * @param {Image} image - The equirectangular image to check.
  16406. * @return {boolean} Whether the image is ready or not.
  16407. */
  16408. function isEquirectangularMapReady$1( image ) {
  16409. if ( image === null || image === undefined ) return false;
  16410. return image.height > 0;
  16411. }
  16412. /**
  16413. * This function is executed when `dispose()` is called on the equirectangular
  16414. * texture. In this case, the generated cube map with its render target
  16415. * is deleted as well.
  16416. *
  16417. * @private
  16418. * @param {Object} event - The event object.
  16419. */
  16420. function onTextureDispose( event ) {
  16421. const texture = event.target;
  16422. texture.removeEventListener( 'dispose', onTextureDispose );
  16423. const renderTarget = _cache$1.get( texture );
  16424. if ( renderTarget !== undefined ) {
  16425. _cache$1.delete( texture );
  16426. renderTarget.dispose();
  16427. }
  16428. }
  16429. /**
  16430. * This function makes sure the generated cube map uses the correct
  16431. * texture mapping that corresponds to the equirectangular original.
  16432. *
  16433. * @private
  16434. * @param {Texture} texture - The cube texture.
  16435. * @param {number} mapping - The original texture mapping.
  16436. */
  16437. function mapTextureMapping( texture, mapping ) {
  16438. if ( mapping === EquirectangularReflectionMapping ) {
  16439. texture.mapping = CubeReflectionMapping;
  16440. } else if ( mapping === EquirectangularRefractionMapping ) {
  16441. texture.mapping = CubeRefractionMapping;
  16442. }
  16443. }
  16444. /**
  16445. * TSL function for creating a cube map node.
  16446. *
  16447. * @tsl
  16448. * @function
  16449. * @param {Node} envNode - The node representing the environment map.
  16450. * @returns {CubeMapNode}
  16451. */
  16452. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  16453. /**
  16454. * Represents a basic model for Image-based lighting (IBL). The environment
  16455. * is defined via environment maps in the equirectangular or cube map format.
  16456. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  16457. * or {@link MeshPhongNodeMaterial}.
  16458. *
  16459. * @augments LightingNode
  16460. */
  16461. class BasicEnvironmentNode extends LightingNode {
  16462. static get type() {
  16463. return 'BasicEnvironmentNode';
  16464. }
  16465. /**
  16466. * Constructs a new basic environment node.
  16467. *
  16468. * @param {Node} [envNode=null] - A node representing the environment.
  16469. */
  16470. constructor( envNode = null ) {
  16471. super();
  16472. /**
  16473. * A node representing the environment.
  16474. *
  16475. * @type {Node}
  16476. * @default null
  16477. */
  16478. this.envNode = envNode;
  16479. }
  16480. setup( builder ) {
  16481. // environment property is used in the finish() method of BasicLightingModel
  16482. builder.context.environment = cubeMapNode( this.envNode );
  16483. }
  16484. }
  16485. /**
  16486. * A specific version of {@link IrradianceNode} that is only relevant
  16487. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  16488. * requires a special scaling factor for the light map.
  16489. *
  16490. * @augments LightingNode
  16491. */
  16492. class BasicLightMapNode extends LightingNode {
  16493. static get type() {
  16494. return 'BasicLightMapNode';
  16495. }
  16496. /**
  16497. * Constructs a new basic light map node.
  16498. *
  16499. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  16500. */
  16501. constructor( lightMapNode = null ) {
  16502. super();
  16503. /**
  16504. * The light map node.
  16505. *
  16506. * @type {?Node<vec3>}
  16507. */
  16508. this.lightMapNode = lightMapNode;
  16509. }
  16510. setup( builder ) {
  16511. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  16512. const RECIPROCAL_PI = float( 1 / Math.PI );
  16513. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  16514. }
  16515. }
  16516. /**
  16517. * Abstract class for implementing lighting models. The module defines
  16518. * multiple methods that concrete lighting models can implement. These
  16519. * methods are executed at different points during the light evaluation
  16520. * process.
  16521. */
  16522. class LightingModel {
  16523. /**
  16524. * This method is intended for setting up lighting model and context data
  16525. * which are later used in the evaluation process.
  16526. *
  16527. * @abstract
  16528. * @param {NodeBuilder} builder - The current node builder.
  16529. */
  16530. start( builder ) {
  16531. // lights ( direct )
  16532. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  16533. // indirect
  16534. this.indirect( builder );
  16535. }
  16536. /**
  16537. * This method is intended for executing final tasks like final updates
  16538. * to the outgoing light.
  16539. *
  16540. * @abstract
  16541. * @param {NodeBuilder} builder - The current node builder.
  16542. */
  16543. finish( /*builder*/ ) { }
  16544. /**
  16545. * This method is intended for implementing the direct light term and
  16546. * executed during the build process of directional, point and spot light nodes.
  16547. *
  16548. * @abstract
  16549. * @param {Object} lightData - The light data.
  16550. * @param {NodeBuilder} builder - The current node builder.
  16551. */
  16552. direct( /*lightData, builder*/ ) { }
  16553. /**
  16554. * This method is intended for implementing the direct light term for
  16555. * rect area light nodes.
  16556. *
  16557. * @abstract
  16558. * @param {Object} lightData - The light data.
  16559. * @param {NodeBuilder} builder - The current node builder.
  16560. */
  16561. directRectArea( /*lightData, builder*/ ) {}
  16562. /**
  16563. * This method is intended for implementing the indirect light term.
  16564. *
  16565. * @abstract
  16566. * @param {NodeBuilder} builder - The current node builder.
  16567. */
  16568. indirect( /*builder*/ ) { }
  16569. /**
  16570. * This method is intended for implementing the ambient occlusion term.
  16571. * Unlike other methods, this method must be called manually by the lighting
  16572. * model in its indirect term.
  16573. *
  16574. * @abstract
  16575. * @param {NodeBuilder} builder - The current node builder.
  16576. */
  16577. ambientOcclusion( /*input, stack, builder*/ ) { }
  16578. }
  16579. /**
  16580. * Represents the lighting model for unlit materials. The only light contribution
  16581. * is baked indirect lighting modulated with ambient occlusion and the material's
  16582. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  16583. *
  16584. * @augments LightingModel
  16585. */
  16586. class BasicLightingModel extends LightingModel {
  16587. /**
  16588. * Constructs a new basic lighting model.
  16589. */
  16590. constructor() {
  16591. super();
  16592. }
  16593. /**
  16594. * Implements the baked indirect lighting with its modulation.
  16595. *
  16596. * @param {NodeBuilder} builder - The current node builder.
  16597. */
  16598. indirect( { context } ) {
  16599. const ambientOcclusion = context.ambientOcclusion;
  16600. const reflectedLight = context.reflectedLight;
  16601. const irradianceLightMap = context.irradianceLightMap;
  16602. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  16603. // accumulation (baked indirect lighting only)
  16604. if ( irradianceLightMap ) {
  16605. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  16606. } else {
  16607. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  16608. }
  16609. // modulation
  16610. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16611. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  16612. }
  16613. /**
  16614. * Implements the environment mapping.
  16615. *
  16616. * @param {NodeBuilder} builder - The current node builder.
  16617. */
  16618. finish( builder ) {
  16619. const { material, context } = builder;
  16620. const outgoingLight = context.outgoingLight;
  16621. const envNode = builder.context.environment;
  16622. if ( envNode ) {
  16623. switch ( material.combine ) {
  16624. case MultiplyOperation:
  16625. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  16626. break;
  16627. case MixOperation:
  16628. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  16629. break;
  16630. case AddOperation:
  16631. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  16632. break;
  16633. default:
  16634. warn( 'BasicLightingModel: Unsupported .combine value:', material.combine );
  16635. break;
  16636. }
  16637. }
  16638. }
  16639. }
  16640. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  16641. /**
  16642. * Node material version of {@link MeshBasicMaterial}.
  16643. *
  16644. * @augments NodeMaterial
  16645. */
  16646. class MeshBasicNodeMaterial extends NodeMaterial {
  16647. static get type() {
  16648. return 'MeshBasicNodeMaterial';
  16649. }
  16650. /**
  16651. * Constructs a new mesh basic node material.
  16652. *
  16653. * @param {Object} [parameters] - The configuration parameter.
  16654. */
  16655. constructor( parameters ) {
  16656. super();
  16657. /**
  16658. * This flag can be used for type testing.
  16659. *
  16660. * @type {boolean}
  16661. * @readonly
  16662. * @default true
  16663. */
  16664. this.isMeshBasicNodeMaterial = true;
  16665. /**
  16666. * Although the basic material is by definition unlit, we set
  16667. * this property to `true` since we use a lighting model to compute
  16668. * the outgoing light of the fragment shader.
  16669. *
  16670. * @type {boolean}
  16671. * @default true
  16672. */
  16673. this.lights = true;
  16674. this.setDefaultValues( _defaultValues$9 );
  16675. this.setValues( parameters );
  16676. }
  16677. /**
  16678. * Basic materials are not affected by normal and bump maps so we
  16679. * return by default {@link normalViewGeometry}.
  16680. *
  16681. * @return {Node<vec3>} The normal node.
  16682. */
  16683. setupNormal() {
  16684. return negateOnBackSide( normalViewGeometry ); // see #28839
  16685. }
  16686. /**
  16687. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16688. * to implement the default environment mapping.
  16689. *
  16690. * @param {NodeBuilder} builder - The current node builder.
  16691. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16692. */
  16693. setupEnvironment( builder ) {
  16694. const envNode = super.setupEnvironment( builder );
  16695. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16696. }
  16697. /**
  16698. * This method must be overwritten since light maps are evaluated
  16699. * with a special scaling factor for basic materials.
  16700. *
  16701. * @param {NodeBuilder} builder - The current node builder.
  16702. * @return {?BasicLightMapNode<vec3>} The light map node.
  16703. */
  16704. setupLightMap( builder ) {
  16705. let node = null;
  16706. if ( builder.material.lightMap ) {
  16707. node = new BasicLightMapNode( materialLightMap );
  16708. }
  16709. return node;
  16710. }
  16711. /**
  16712. * The material overwrites this method because `lights` is set to `true` but
  16713. * we still want to return the diffuse color as the outgoing light.
  16714. *
  16715. * @return {Node<vec3>} The outgoing light node.
  16716. */
  16717. setupOutgoingLight() {
  16718. return diffuseColor.rgb;
  16719. }
  16720. /**
  16721. * Setups the lighting model.
  16722. *
  16723. * @return {BasicLightingModel} The lighting model.
  16724. */
  16725. setupLightingModel() {
  16726. return new BasicLightingModel();
  16727. }
  16728. }
  16729. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  16730. // Original approximation by Christophe Schlick '94
  16731. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  16732. // Optimized variant (presented by Epic at SIGGRAPH '13)
  16733. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  16734. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  16735. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  16736. } ); // validated
  16737. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  16738. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  16739. } ); // validated
  16740. const G_BlinnPhong_Implicit = () => float( 0.25 );
  16741. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  16742. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  16743. } );
  16744. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16745. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16746. const dotNH = normalView.dot( halfDir ).clamp();
  16747. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16748. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  16749. const G = G_BlinnPhong_Implicit();
  16750. const D = D_BlinnPhong( { dotNH } );
  16751. return F.mul( G ).mul( D );
  16752. } );
  16753. /**
  16754. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  16755. *
  16756. * @augments BasicLightingModel
  16757. */
  16758. class PhongLightingModel extends BasicLightingModel {
  16759. /**
  16760. * Constructs a new phong lighting model.
  16761. *
  16762. * @param {boolean} [specular=true] - Whether specular is supported or not.
  16763. */
  16764. constructor( specular = true ) {
  16765. super();
  16766. /**
  16767. * Whether specular is supported or not. Set this to `false` if you are
  16768. * looking for a Lambert-like material meaning a material for non-shiny
  16769. * surfaces, without specular highlights.
  16770. *
  16771. * @type {boolean}
  16772. * @default true
  16773. */
  16774. this.specular = specular;
  16775. }
  16776. /**
  16777. * Implements the direct lighting. The specular portion is optional an can be controlled
  16778. * with the {@link PhongLightingModel#specular} flag.
  16779. *
  16780. * @param {Object} lightData - The light data.
  16781. */
  16782. direct( { lightDirection, lightColor, reflectedLight } ) {
  16783. const dotNL = normalView.dot( lightDirection ).clamp();
  16784. const irradiance = dotNL.mul( lightColor );
  16785. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16786. if ( this.specular === true ) {
  16787. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  16788. }
  16789. }
  16790. /**
  16791. * Implements the indirect lighting.
  16792. *
  16793. * @param {NodeBuilder} builder - The current node builder.
  16794. */
  16795. indirect( builder ) {
  16796. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  16797. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16798. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16799. }
  16800. }
  16801. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  16802. /**
  16803. * Node material version of {@link MeshLambertMaterial}.
  16804. *
  16805. * @augments NodeMaterial
  16806. */
  16807. class MeshLambertNodeMaterial extends NodeMaterial {
  16808. static get type() {
  16809. return 'MeshLambertNodeMaterial';
  16810. }
  16811. /**
  16812. * Constructs a new mesh lambert node material.
  16813. *
  16814. * @param {Object} [parameters] - The configuration parameter.
  16815. */
  16816. constructor( parameters ) {
  16817. super();
  16818. /**
  16819. * This flag can be used for type testing.
  16820. *
  16821. * @type {boolean}
  16822. * @readonly
  16823. * @default true
  16824. */
  16825. this.isMeshLambertNodeMaterial = true;
  16826. /**
  16827. * Set to `true` because lambert materials react on lights.
  16828. *
  16829. * @type {boolean}
  16830. * @default true
  16831. */
  16832. this.lights = true;
  16833. this.setDefaultValues( _defaultValues$8 );
  16834. this.setValues( parameters );
  16835. }
  16836. /**
  16837. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16838. * to implement the default environment mapping.
  16839. *
  16840. * @param {NodeBuilder} builder - The current node builder.
  16841. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16842. */
  16843. setupEnvironment( builder ) {
  16844. const envNode = super.setupEnvironment( builder );
  16845. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16846. }
  16847. /**
  16848. * Setups the lighting model.
  16849. *
  16850. * @return {PhongLightingModel} The lighting model.
  16851. */
  16852. setupLightingModel( /*builder*/ ) {
  16853. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  16854. }
  16855. }
  16856. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  16857. /**
  16858. * Node material version of {@link MeshPhongMaterial}.
  16859. *
  16860. * @augments NodeMaterial
  16861. */
  16862. class MeshPhongNodeMaterial extends NodeMaterial {
  16863. static get type() {
  16864. return 'MeshPhongNodeMaterial';
  16865. }
  16866. /**
  16867. * Constructs a new mesh lambert node material.
  16868. *
  16869. * @param {Object} [parameters] - The configuration parameter.
  16870. */
  16871. constructor( parameters ) {
  16872. super();
  16873. /**
  16874. * This flag can be used for type testing.
  16875. *
  16876. * @type {boolean}
  16877. * @readonly
  16878. * @default true
  16879. */
  16880. this.isMeshPhongNodeMaterial = true;
  16881. /**
  16882. * Set to `true` because phong materials react on lights.
  16883. *
  16884. * @type {boolean}
  16885. * @default true
  16886. */
  16887. this.lights = true;
  16888. /**
  16889. * The shininess of phong materials is by default inferred from the `shininess`
  16890. * property. This node property allows to overwrite the default
  16891. * and define the shininess with a node instead.
  16892. *
  16893. * If you don't want to overwrite the shininess but modify the existing
  16894. * value instead, use {@link materialShininess}.
  16895. *
  16896. * @type {?Node<float>}
  16897. * @default null
  16898. */
  16899. this.shininessNode = null;
  16900. /**
  16901. * The specular color of phong materials is by default inferred from the
  16902. * `specular` property. This node property allows to overwrite the default
  16903. * and define the specular color with a node instead.
  16904. *
  16905. * If you don't want to overwrite the specular color but modify the existing
  16906. * value instead, use {@link materialSpecular}.
  16907. *
  16908. * @type {?Node<vec3>}
  16909. * @default null
  16910. */
  16911. this.specularNode = null;
  16912. this.setDefaultValues( _defaultValues$7 );
  16913. this.setValues( parameters );
  16914. }
  16915. /**
  16916. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16917. * to implement the default environment mapping.
  16918. *
  16919. * @param {NodeBuilder} builder - The current node builder.
  16920. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16921. */
  16922. setupEnvironment( builder ) {
  16923. const envNode = super.setupEnvironment( builder );
  16924. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16925. }
  16926. /**
  16927. * Setups the lighting model.
  16928. *
  16929. * @return {PhongLightingModel} The lighting model.
  16930. */
  16931. setupLightingModel( /*builder*/ ) {
  16932. return new PhongLightingModel();
  16933. }
  16934. /**
  16935. * Setups the phong specific node variables.
  16936. *
  16937. * @param {NodeBuilder} builder - The current node builder.
  16938. */
  16939. setupVariants( /*builder*/ ) {
  16940. // SHININESS
  16941. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16942. shininess.assign( shininessNode );
  16943. // SPECULAR COLOR
  16944. const specularNode = this.specularNode || materialSpecular;
  16945. specularColor.assign( specularNode );
  16946. }
  16947. }
  16948. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  16949. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  16950. return float( 0 );
  16951. }
  16952. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  16953. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  16954. return geometryRoughness;
  16955. } );
  16956. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  16957. const { roughness } = inputs;
  16958. const geometryRoughness = getGeometryRoughness();
  16959. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  16960. roughnessFactor = roughnessFactor.add( geometryRoughness );
  16961. roughnessFactor = roughnessFactor.min( 1.0 );
  16962. return roughnessFactor;
  16963. } );
  16964. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  16965. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  16966. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  16967. const a2 = alpha.pow2();
  16968. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  16969. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  16970. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  16971. } ).setLayout( {
  16972. name: 'V_GGX_SmithCorrelated',
  16973. type: 'float',
  16974. inputs: [
  16975. { name: 'alpha', type: 'float' },
  16976. { name: 'dotNL', type: 'float' },
  16977. { name: 'dotNV', type: 'float' }
  16978. ]
  16979. } ); // validated
  16980. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16981. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  16982. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  16983. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  16984. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  16985. } ).setLayout( {
  16986. name: 'V_GGX_SmithCorrelated_Anisotropic',
  16987. type: 'float',
  16988. inputs: [
  16989. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16990. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16991. { name: 'dotTV', type: 'float', qualifier: 'in' },
  16992. { name: 'dotBV', type: 'float', qualifier: 'in' },
  16993. { name: 'dotTL', type: 'float', qualifier: 'in' },
  16994. { name: 'dotBL', type: 'float', qualifier: 'in' },
  16995. { name: 'dotNV', type: 'float', qualifier: 'in' },
  16996. { name: 'dotNL', type: 'float', qualifier: 'in' }
  16997. ]
  16998. } );
  16999. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  17000. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  17001. // alpha is "roughness squared" in Disney’s reparameterization
  17002. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  17003. const a2 = alpha.pow2();
  17004. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  17005. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  17006. } ).setLayout( {
  17007. name: 'D_GGX',
  17008. type: 'float',
  17009. inputs: [
  17010. { name: 'alpha', type: 'float' },
  17011. { name: 'dotNH', type: 'float' }
  17012. ]
  17013. } ); // validated
  17014. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  17015. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  17016. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  17017. const a2 = alphaT.mul( alphaB );
  17018. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  17019. const v2 = v.dot( v );
  17020. const w2 = a2.div( v2 );
  17021. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  17022. } ).setLayout( {
  17023. name: 'D_GGX_Anisotropic',
  17024. type: 'float',
  17025. inputs: [
  17026. { name: 'alphaT', type: 'float', qualifier: 'in' },
  17027. { name: 'alphaB', type: 'float', qualifier: 'in' },
  17028. { name: 'dotNH', type: 'float', qualifier: 'in' },
  17029. { name: 'dotTH', type: 'float', qualifier: 'in' },
  17030. { name: 'dotBH', type: 'float', qualifier: 'in' }
  17031. ]
  17032. } );
  17033. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  17034. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  17035. const alpha = roughness.pow2(); // UE4's roughness
  17036. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  17037. const dotNL = normalView$1.dot( lightDirection ).clamp();
  17038. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17039. const dotNH = normalView$1.dot( halfDir ).clamp();
  17040. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  17041. let F = F_Schlick( { f0, f90, dotVH } );
  17042. let V, D;
  17043. if ( defined( USE_IRIDESCENCE ) ) {
  17044. F = iridescence.mix( F, f );
  17045. }
  17046. if ( defined( USE_ANISOTROPY ) ) {
  17047. const dotTL = anisotropyT.dot( lightDirection );
  17048. const dotTV = anisotropyT.dot( positionViewDirection );
  17049. const dotTH = anisotropyT.dot( halfDir );
  17050. const dotBL = anisotropyB.dot( lightDirection );
  17051. const dotBV = anisotropyB.dot( positionViewDirection );
  17052. const dotBH = anisotropyB.dot( halfDir );
  17053. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  17054. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  17055. } else {
  17056. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  17057. D = D_GGX( { alpha, dotNH } );
  17058. }
  17059. return F.mul( V ).mul( D );
  17060. } ); // validated
  17061. /**
  17062. * Precomputed DFG LUT for Image-Based Lighting
  17063. * Resolution: 16x16
  17064. * Samples: 4096 per texel
  17065. * Format: RG16F (2 half floats per texel: scale, bias)
  17066. */
  17067. const DATA = new Uint16Array( [
  17068. 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,
  17069. 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,
  17070. 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,
  17071. 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,
  17072. 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,
  17073. 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,
  17074. 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,
  17075. 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,
  17076. 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,
  17077. 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,
  17078. 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,
  17079. 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,
  17080. 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,
  17081. 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,
  17082. 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,
  17083. 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
  17084. ] );
  17085. let lut = null;
  17086. const DFGLUT = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  17087. if ( lut === null ) {
  17088. lut = new DataTexture( DATA, 16, 16, RGFormat, HalfFloatType );
  17089. lut.name = 'DFG_LUT';
  17090. lut.minFilter = LinearFilter;
  17091. lut.magFilter = LinearFilter;
  17092. lut.wrapS = ClampToEdgeWrapping;
  17093. lut.wrapT = ClampToEdgeWrapping;
  17094. lut.generateMipmaps = false;
  17095. lut.needsUpdate = true;
  17096. }
  17097. const uv = vec2( roughness, dotNV );
  17098. return texture( lut, uv ).rg;
  17099. } );
  17100. // GGX BRDF with multi-scattering energy compensation for direct lighting
  17101. // This provides more accurate energy conservation, especially for rough materials
  17102. // Based on "Practical Multiple Scattering Compensation for Microfacet Models"
  17103. // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf
  17104. const BRDF_GGX_Multiscatter = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  17105. // Single-scattering BRDF (standard GGX)
  17106. const singleScatter = BRDF_GGX( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } );
  17107. // Multi-scattering compensation
  17108. const dotNL = normalView.dot( lightDirection ).clamp();
  17109. const dotNV = normalView.dot( positionViewDirection ).clamp();
  17110. // Precomputed DFG values for view and light directions
  17111. const dfgV = DFGLUT( { roughness: _roughness, dotNV } );
  17112. const dfgL = DFGLUT( { roughness: _roughness, dotNV: dotNL } );
  17113. // Single-scattering energy for view and light
  17114. const FssEss_V = f0.mul( dfgV.x ).add( f90.mul( dfgV.y ) );
  17115. const FssEss_L = f0.mul( dfgL.x ).add( f90.mul( dfgL.y ) );
  17116. const Ess_V = dfgV.x.add( dfgV.y );
  17117. const Ess_L = dfgL.x.add( dfgL.y );
  17118. // Energy lost to multiple scattering
  17119. const Ems_V = float( 1.0 ).sub( Ess_V );
  17120. const Ems_L = float( 1.0 ).sub( Ess_L );
  17121. // Average Fresnel reflectance
  17122. const Favg = f0.add( f0.oneMinus().mul( 0.047619 ) ); // 1/21
  17123. // Multiple scattering contribution
  17124. // Uses geometric mean of view and light contributions for better energy distribution
  17125. const Fms = FssEss_V.mul( FssEss_L ).mul( Favg ).div( float( 1.0 ).sub( Ems_V.mul( Ems_L ).mul( Favg ).mul( Favg ) ).add( EPSILON ) );
  17126. // Energy compensation factor
  17127. const compensationFactor = Ems_V.mul( Ems_L );
  17128. const multiScatter = Fms.mul( compensationFactor );
  17129. return singleScatter.add( multiScatter );
  17130. } );
  17131. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  17132. const { dotNV, specularColor, specularF90, roughness } = inputs;
  17133. const fab = DFGLUT( { dotNV, roughness } );
  17134. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  17135. } );
  17136. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  17137. const x = dotVH.oneMinus().saturate();
  17138. const x2 = x.mul( x );
  17139. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  17140. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  17141. } ).setLayout( {
  17142. name: 'Schlick_to_F0',
  17143. type: 'vec3',
  17144. inputs: [
  17145. { name: 'f', type: 'vec3' },
  17146. { name: 'f90', type: 'float' },
  17147. { name: 'dotVH', type: 'float' }
  17148. ]
  17149. } );
  17150. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  17151. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  17152. const alpha = roughness.pow2();
  17153. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  17154. const invAlpha = float( 1.0 ).div( alpha );
  17155. const cos2h = dotNH.pow2();
  17156. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  17157. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  17158. } ).setLayout( {
  17159. name: 'D_Charlie',
  17160. type: 'float',
  17161. inputs: [
  17162. { name: 'roughness', type: 'float' },
  17163. { name: 'dotNH', type: 'float' }
  17164. ]
  17165. } );
  17166. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  17167. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  17168. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  17169. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  17170. } ).setLayout( {
  17171. name: 'V_Neubelt',
  17172. type: 'float',
  17173. inputs: [
  17174. { name: 'dotNV', type: 'float' },
  17175. { name: 'dotNL', type: 'float' }
  17176. ]
  17177. } );
  17178. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  17179. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  17180. const dotNL = normalView.dot( lightDirection ).clamp();
  17181. const dotNV = normalView.dot( positionViewDirection ).clamp();
  17182. const dotNH = normalView.dot( halfDir ).clamp();
  17183. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  17184. const V = V_Neubelt( { dotNV, dotNL } );
  17185. return sheen.mul( D ).mul( V );
  17186. } );
  17187. // Rect Area Light
  17188. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  17189. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  17190. // code: https://github.com/selfshadow/ltc_code/
  17191. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  17192. const LUT_SIZE = 64.0;
  17193. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  17194. const LUT_BIAS = 0.5 / LUT_SIZE;
  17195. const dotNV = N.dot( V ).saturate();
  17196. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  17197. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  17198. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  17199. return uv;
  17200. } ).setLayout( {
  17201. name: 'LTC_Uv',
  17202. type: 'vec2',
  17203. inputs: [
  17204. { name: 'N', type: 'vec3' },
  17205. { name: 'V', type: 'vec3' },
  17206. { name: 'roughness', type: 'float' }
  17207. ]
  17208. } );
  17209. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  17210. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  17211. // An approximation of the form factor of a horizon-clipped rectangle.
  17212. const l = f.length();
  17213. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  17214. } ).setLayout( {
  17215. name: 'LTC_ClippedSphereFormFactor',
  17216. type: 'float',
  17217. inputs: [
  17218. { name: 'f', type: 'vec3' }
  17219. ]
  17220. } );
  17221. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  17222. const x = v1.dot( v2 );
  17223. const y = x.abs().toVar();
  17224. // rational polynomial approximation to theta / sin( theta ) / 2PI
  17225. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  17226. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  17227. const v = a.div( b );
  17228. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  17229. return v1.cross( v2 ).mul( theta_sintheta );
  17230. } ).setLayout( {
  17231. name: 'LTC_EdgeVectorFormFactor',
  17232. type: 'vec3',
  17233. inputs: [
  17234. { name: 'v1', type: 'vec3' },
  17235. { name: 'v2', type: 'vec3' }
  17236. ]
  17237. } );
  17238. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  17239. // bail if point is on back side of plane of light
  17240. // assumes ccw winding order of light vertices
  17241. const v1 = p1.sub( p0 ).toVar();
  17242. const v2 = p3.sub( p0 ).toVar();
  17243. const lightNormal = v1.cross( v2 );
  17244. const result = vec3().toVar();
  17245. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  17246. // construct orthonormal basis around N
  17247. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  17248. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  17249. // compute transform
  17250. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  17251. // transform rect
  17252. // & project rect onto sphere
  17253. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  17254. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  17255. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  17256. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  17257. // calculate vector form factor
  17258. const vectorFormFactor = vec3( 0 ).toVar();
  17259. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  17260. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  17261. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  17262. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  17263. // adjust for horizon clipping
  17264. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  17265. } );
  17266. return result;
  17267. } ).setLayout( {
  17268. name: 'LTC_Evaluate',
  17269. type: 'vec3',
  17270. inputs: [
  17271. { name: 'N', type: 'vec3' },
  17272. { name: 'V', type: 'vec3' },
  17273. { name: 'P', type: 'vec3' },
  17274. { name: 'mInv', type: 'mat3' },
  17275. { name: 'p0', type: 'vec3' },
  17276. { name: 'p1', type: 'vec3' },
  17277. { name: 'p2', type: 'vec3' },
  17278. { name: 'p3', type: 'vec3' }
  17279. ]
  17280. } );
  17281. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  17282. // bail if point is on back side of plane of light
  17283. // assumes ccw winding order of light vertices
  17284. const v1 = p1.sub( p0 ).toVar();
  17285. const v2 = p3.sub( p0 ).toVar();
  17286. const lightNormal = v1.cross( v2 );
  17287. const result = vec3().toVar();
  17288. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  17289. // transform rect
  17290. // & project rect onto sphere
  17291. const coords0 = p0.sub( P ).normalize().toVar();
  17292. const coords1 = p1.sub( P ).normalize().toVar();
  17293. const coords2 = p2.sub( P ).normalize().toVar();
  17294. const coords3 = p3.sub( P ).normalize().toVar();
  17295. // calculate vector form factor
  17296. const vectorFormFactor = vec3( 0 ).toVar();
  17297. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  17298. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  17299. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  17300. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  17301. // adjust for horizon clipping
  17302. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  17303. } );
  17304. return result;
  17305. } ).setLayout( {
  17306. name: 'LTC_Evaluate',
  17307. type: 'vec3',
  17308. inputs: [
  17309. { name: 'P', type: 'vec3' },
  17310. { name: 'p0', type: 'vec3' },
  17311. { name: 'p1', type: 'vec3' },
  17312. { name: 'p2', type: 'vec3' },
  17313. { name: 'p3', type: 'vec3' }
  17314. ]
  17315. } );
  17316. // Mipped Bicubic Texture Filtering by N8
  17317. // https://www.shadertoy.com/view/Dl2SDW
  17318. const bC = 1.0 / 6.0;
  17319. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  17320. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  17321. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  17322. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  17323. const g0 = ( a ) => w0( a ).add( w1( a ) );
  17324. const g1 = ( a ) => w2( a ).add( w3( a ) );
  17325. // h0 and h1 are the two offset functions
  17326. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  17327. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  17328. const bicubic = ( textureNode, texelSize, lod ) => {
  17329. const uv = textureNode.uvNode;
  17330. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  17331. const iuv = floor( uvScaled );
  17332. const fuv = fract( uvScaled );
  17333. const g0x = g0( fuv.x );
  17334. const g1x = g1( fuv.x );
  17335. const h0x = h0( fuv.x );
  17336. const h1x = h1( fuv.x );
  17337. const h0y = h0( fuv.y );
  17338. const h1y = h1( fuv.y );
  17339. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  17340. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  17341. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  17342. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  17343. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  17344. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  17345. return a.add( b );
  17346. };
  17347. /**
  17348. * Applies mipped bicubic texture filtering to the given texture node.
  17349. *
  17350. * @tsl
  17351. * @function
  17352. * @param {TextureNode} textureNode - The texture node that should be filtered.
  17353. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  17354. * @return {Node} The filtered texture sample.
  17355. */
  17356. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  17357. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  17358. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  17359. const fLodSizeInv = div( 1.0, fLodSize );
  17360. const cLodSizeInv = div( 1.0, cLodSize );
  17361. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  17362. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  17363. return fract( lodNode ).mix( fSample, cSample );
  17364. } );
  17365. /**
  17366. * Applies mipped bicubic texture filtering to the given texture node.
  17367. *
  17368. * @tsl
  17369. * @function
  17370. * @param {TextureNode} textureNode - The texture node that should be filtered.
  17371. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  17372. * @return {Node} The filtered texture sample.
  17373. */
  17374. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  17375. const lod = strength.mul( maxMipLevel( textureNode ) );
  17376. return textureBicubicLevel( textureNode, lod );
  17377. } );
  17378. //
  17379. // Transmission
  17380. //
  17381. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  17382. // Direction of refracted light.
  17383. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  17384. // Compute rotation-independent scaling of the model matrix.
  17385. const modelScale = vec3(
  17386. length( modelMatrix[ 0 ].xyz ),
  17387. length( modelMatrix[ 1 ].xyz ),
  17388. length( modelMatrix[ 2 ].xyz )
  17389. );
  17390. // The thickness is specified in local space.
  17391. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  17392. } ).setLayout( {
  17393. name: 'getVolumeTransmissionRay',
  17394. type: 'vec3',
  17395. inputs: [
  17396. { name: 'n', type: 'vec3' },
  17397. { name: 'v', type: 'vec3' },
  17398. { name: 'thickness', type: 'float' },
  17399. { name: 'ior', type: 'float' },
  17400. { name: 'modelMatrix', type: 'mat4' }
  17401. ]
  17402. } );
  17403. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  17404. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  17405. // an IOR of 1.5 results in the default amount of microfacet refraction.
  17406. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  17407. } ).setLayout( {
  17408. name: 'applyIorToRoughness',
  17409. type: 'float',
  17410. inputs: [
  17411. { name: 'roughness', type: 'float' },
  17412. { name: 'ior', type: 'float' }
  17413. ]
  17414. } );
  17415. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  17416. const viewportFrontSideTexture = /*@__PURE__*/ viewportOpaqueMipTexture();
  17417. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  17418. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  17419. const transmissionSample = vTexture.sample( fragCoord );
  17420. //const transmissionSample = viewportMipTexture( fragCoord );
  17421. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  17422. return textureBicubicLevel( transmissionSample, lod );
  17423. } );
  17424. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  17425. If( attenuationDistance.notEqual( 0 ), () => {
  17426. // Compute light attenuation using Beer's law.
  17427. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  17428. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  17429. return transmittance;
  17430. } );
  17431. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  17432. return vec3( 1.0 );
  17433. } ).setLayout( {
  17434. name: 'volumeAttenuation',
  17435. type: 'vec3',
  17436. inputs: [
  17437. { name: 'transmissionDistance', type: 'float' },
  17438. { name: 'attenuationColor', type: 'vec3' },
  17439. { name: 'attenuationDistance', type: 'float' }
  17440. ]
  17441. } );
  17442. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  17443. let transmittedLight, transmittance;
  17444. if ( dispersion ) {
  17445. transmittedLight = vec4().toVar();
  17446. transmittance = vec3().toVar();
  17447. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  17448. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  17449. Loop( { start: 0, end: 3 }, ( { i } ) => {
  17450. const ior = iors.element( i );
  17451. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  17452. const refractedRayExit = position.add( transmissionRay );
  17453. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  17454. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  17455. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  17456. refractionCoords.addAssign( 1.0 );
  17457. refractionCoords.divAssign( 2.0 );
  17458. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  17459. // Sample framebuffer to get pixel the refracted ray hits.
  17460. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  17461. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  17462. transmittedLight.a.addAssign( transmissionSample.a );
  17463. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  17464. } );
  17465. transmittedLight.a.divAssign( 3.0 );
  17466. } else {
  17467. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  17468. const refractedRayExit = position.add( transmissionRay );
  17469. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  17470. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  17471. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  17472. refractionCoords.addAssign( 1.0 );
  17473. refractionCoords.divAssign( 2.0 );
  17474. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  17475. // Sample framebuffer to get pixel the refracted ray hits.
  17476. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  17477. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  17478. }
  17479. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  17480. const dotNV = n.dot( v ).clamp();
  17481. // Get the specular component.
  17482. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  17483. dotNV,
  17484. specularColor,
  17485. specularF90,
  17486. roughness
  17487. } ) );
  17488. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  17489. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  17490. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  17491. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  17492. } );
  17493. //
  17494. // Iridescence
  17495. //
  17496. // XYZ to linear-sRGB color space
  17497. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  17498. 3.2404542, -0.969266, 0.0556434,
  17499. -1.5371385, 1.8760108, -0.2040259,
  17500. -0.4985314, 0.0415560, 1.0572252
  17501. );
  17502. // Assume air interface for top
  17503. // Note: We don't handle the case fresnel0 == 1
  17504. const Fresnel0ToIor = ( fresnel0 ) => {
  17505. const sqrtF0 = fresnel0.sqrt();
  17506. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  17507. };
  17508. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  17509. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  17510. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  17511. };
  17512. // Fresnel equations for dielectric/dielectric interfaces.
  17513. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  17514. // Evaluation XYZ sensitivity curves in Fourier space
  17515. const evalSensitivity = ( OPD, shift ) => {
  17516. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  17517. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  17518. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  17519. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  17520. 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() );
  17521. 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() );
  17522. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  17523. const rgb = XYZ_TO_REC709.mul( xyz );
  17524. return rgb;
  17525. };
  17526. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  17527. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  17528. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  17529. // Evaluate the cosTheta on the base layer (Snell law)
  17530. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  17531. // Handle TIR:
  17532. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  17533. If( cosTheta2Sq.lessThan( 0 ), () => {
  17534. return vec3( 1.0 );
  17535. } );
  17536. const cosTheta2 = cosTheta2Sq.sqrt();
  17537. // First interface
  17538. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  17539. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  17540. //const R21 = R12;
  17541. const T121 = R12.oneMinus();
  17542. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  17543. const phi21 = float( Math.PI ).sub( phi12 );
  17544. // Second interface
  17545. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  17546. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  17547. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  17548. const phi23 = vec3(
  17549. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  17550. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  17551. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  17552. );
  17553. // Phase shift
  17554. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  17555. const phi = vec3( phi21 ).add( phi23 );
  17556. // Compound terms
  17557. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  17558. const r123 = R123.sqrt();
  17559. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  17560. // Reflectance term for m = 0 (DC term amplitude)
  17561. const C0 = R12.add( Rs );
  17562. const I = C0.toVar();
  17563. // Reflectance term for m > 0 (pairs of diracs)
  17564. const Cm = Rs.sub( T121 ).toVar();
  17565. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  17566. Cm.mulAssign( r123 );
  17567. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  17568. I.addAssign( Cm.mul( Sm ) );
  17569. } );
  17570. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  17571. return I.max( vec3( 0.0 ) );
  17572. } ).setLayout( {
  17573. name: 'evalIridescence',
  17574. type: 'vec3',
  17575. inputs: [
  17576. { name: 'outsideIOR', type: 'float' },
  17577. { name: 'eta2', type: 'float' },
  17578. { name: 'cosTheta1', type: 'float' },
  17579. { name: 'thinFilmThickness', type: 'float' },
  17580. { name: 'baseF0', type: 'vec3' }
  17581. ]
  17582. } );
  17583. //
  17584. // Sheen
  17585. //
  17586. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  17587. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF".
  17588. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  17589. const dotNV = normal.dot( viewDir ).saturate();
  17590. const r2 = roughness.mul( roughness );
  17591. const rInv = roughness.add( 0.1 ).reciprocal();
  17592. const a = float( -1.9362 ).add( roughness.mul( 1.0678 ) ).add( r2.mul( 0.4573 ) ).sub( rInv.mul( 0.8469 ) );
  17593. const b = float( -0.6014 ).add( roughness.mul( 0.5538 ) ).sub( r2.mul( 0.4670 ) ).sub( rInv.mul( 0.1255 ) );
  17594. const DG = a.mul( dotNV ).add( b ).exp();
  17595. return DG.saturate();
  17596. } );
  17597. const clearcoatF0 = vec3( 0.04 );
  17598. const clearcoatF90 = float( 1 );
  17599. /**
  17600. * Represents the lighting model for a PBR material.
  17601. *
  17602. * @augments LightingModel
  17603. */
  17604. class PhysicalLightingModel extends LightingModel {
  17605. /**
  17606. * Constructs a new physical lighting model.
  17607. *
  17608. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  17609. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  17610. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  17611. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  17612. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  17613. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  17614. */
  17615. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  17616. super();
  17617. /**
  17618. * Whether clearcoat is supported or not.
  17619. *
  17620. * @type {boolean}
  17621. * @default false
  17622. */
  17623. this.clearcoat = clearcoat;
  17624. /**
  17625. * Whether sheen is supported or not.
  17626. *
  17627. * @type {boolean}
  17628. * @default false
  17629. */
  17630. this.sheen = sheen;
  17631. /**
  17632. * Whether iridescence is supported or not.
  17633. *
  17634. * @type {boolean}
  17635. * @default false
  17636. */
  17637. this.iridescence = iridescence;
  17638. /**
  17639. * Whether anisotropy is supported or not.
  17640. *
  17641. * @type {boolean}
  17642. * @default false
  17643. */
  17644. this.anisotropy = anisotropy;
  17645. /**
  17646. * Whether transmission is supported or not.
  17647. *
  17648. * @type {boolean}
  17649. * @default false
  17650. */
  17651. this.transmission = transmission;
  17652. /**
  17653. * Whether dispersion is supported or not.
  17654. *
  17655. * @type {boolean}
  17656. * @default false
  17657. */
  17658. this.dispersion = dispersion;
  17659. /**
  17660. * The clear coat radiance.
  17661. *
  17662. * @type {?Node}
  17663. * @default null
  17664. */
  17665. this.clearcoatRadiance = null;
  17666. /**
  17667. * The clear coat specular direct.
  17668. *
  17669. * @type {?Node}
  17670. * @default null
  17671. */
  17672. this.clearcoatSpecularDirect = null;
  17673. /**
  17674. * The clear coat specular indirect.
  17675. *
  17676. * @type {?Node}
  17677. * @default null
  17678. */
  17679. this.clearcoatSpecularIndirect = null;
  17680. /**
  17681. * The sheen specular direct.
  17682. *
  17683. * @type {?Node}
  17684. * @default null
  17685. */
  17686. this.sheenSpecularDirect = null;
  17687. /**
  17688. * The sheen specular indirect.
  17689. *
  17690. * @type {?Node}
  17691. * @default null
  17692. */
  17693. this.sheenSpecularIndirect = null;
  17694. /**
  17695. * The iridescence Fresnel.
  17696. *
  17697. * @type {?Node}
  17698. * @default null
  17699. */
  17700. this.iridescenceFresnel = null;
  17701. /**
  17702. * The iridescence F0.
  17703. *
  17704. * @type {?Node}
  17705. * @default null
  17706. */
  17707. this.iridescenceF0 = null;
  17708. /**
  17709. * The iridescence F0 dielectric.
  17710. *
  17711. * @type {?Node}
  17712. * @default null
  17713. */
  17714. this.iridescenceF0Dielectric = null;
  17715. /**
  17716. * The iridescence F0 metallic.
  17717. *
  17718. * @type {?Node}
  17719. * @default null
  17720. */
  17721. this.iridescenceF0Metallic = null;
  17722. }
  17723. /**
  17724. * Depending on what features are requested, the method prepares certain node variables
  17725. * which are later used for lighting computations.
  17726. *
  17727. * @param {NodeBuilder} builder - The current node builder.
  17728. */
  17729. start( builder ) {
  17730. if ( this.clearcoat === true ) {
  17731. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  17732. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  17733. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  17734. }
  17735. if ( this.sheen === true ) {
  17736. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  17737. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  17738. }
  17739. if ( this.iridescence === true ) {
  17740. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  17741. const iridescenceFresnelDielectric = evalIridescence( {
  17742. outsideIOR: float( 1.0 ),
  17743. eta2: iridescenceIOR,
  17744. cosTheta1: dotNVi,
  17745. thinFilmThickness: iridescenceThickness,
  17746. baseF0: specularColor
  17747. } );
  17748. const iridescenceFresnelMetallic = evalIridescence( {
  17749. outsideIOR: float( 1.0 ),
  17750. eta2: iridescenceIOR,
  17751. cosTheta1: dotNVi,
  17752. thinFilmThickness: iridescenceThickness,
  17753. baseF0: diffuseColor.rgb
  17754. } );
  17755. this.iridescenceFresnel = mix( iridescenceFresnelDielectric, iridescenceFresnelMetallic, metalness );
  17756. this.iridescenceF0Dielectric = Schlick_to_F0( { f: iridescenceFresnelDielectric, f90: 1.0, dotVH: dotNVi } );
  17757. this.iridescenceF0Metallic = Schlick_to_F0( { f: iridescenceFresnelMetallic, f90: 1.0, dotVH: dotNVi } );
  17758. this.iridescenceF0 = mix( this.iridescenceF0Dielectric, this.iridescenceF0Metallic, metalness );
  17759. }
  17760. if ( this.transmission === true ) {
  17761. const position = positionWorld;
  17762. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  17763. const n = normalWorld;
  17764. const context = builder.context;
  17765. context.backdrop = getIBLVolumeRefraction(
  17766. n,
  17767. v,
  17768. roughness,
  17769. diffuseContribution,
  17770. specularColorBlended,
  17771. specularF90, // specularF90
  17772. position, // positionWorld
  17773. modelWorldMatrix, // modelMatrix
  17774. cameraViewMatrix, // viewMatrix
  17775. cameraProjectionMatrix, // projMatrix
  17776. ior,
  17777. thickness,
  17778. attenuationColor,
  17779. attenuationDistance,
  17780. this.dispersion ? dispersion : null
  17781. );
  17782. context.backdropAlpha = transmission;
  17783. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  17784. }
  17785. super.start( builder );
  17786. }
  17787. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  17788. // Approximates multi-scattering in order to preserve energy.
  17789. // http://www.jcgt.org/published/0008/01/03/
  17790. computeMultiscattering( singleScatter, multiScatter, specularF90, f0, iridescenceF0 = null ) {
  17791. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17792. const fab = DFGLUT( { roughness, dotNV } );
  17793. const Fr = iridescenceF0 ? iridescence.mix( f0, iridescenceF0 ) : f0;
  17794. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  17795. const Ess = fab.x.add( fab.y );
  17796. const Ems = Ess.oneMinus();
  17797. const Favg = Fr.add( Fr.oneMinus().mul( 0.047619 ) ); // 1/21
  17798. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  17799. singleScatter.addAssign( FssEss );
  17800. multiScatter.addAssign( Fms.mul( Ems ) );
  17801. }
  17802. /**
  17803. * Implements the direct light.
  17804. *
  17805. * @param {Object} lightData - The light data.
  17806. * @param {NodeBuilder} builder - The current node builder.
  17807. */
  17808. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  17809. const dotNL = normalView.dot( lightDirection ).clamp();
  17810. const irradiance = dotNL.mul( lightColor ).toVar();
  17811. if ( this.sheen === true ) {
  17812. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  17813. const sheenAlbedoV = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17814. const sheenAlbedoL = IBLSheenBRDF( { normal: normalView, viewDir: lightDirection, roughness: sheenRoughness } );
  17815. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedoV.max( sheenAlbedoL ) ).oneMinus();
  17816. irradiance.mulAssign( sheenEnergyComp );
  17817. }
  17818. if ( this.clearcoat === true ) {
  17819. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  17820. const ccIrradiance = dotNLcc.mul( lightColor );
  17821. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  17822. }
  17823. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ) );
  17824. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_GGX_Multiscatter( { lightDirection, f0: specularColorBlended, f90: 1, roughness, f: this.iridescenceFresnel, USE_IRIDESCENCE: this.iridescence, USE_ANISOTROPY: this.anisotropy } ) ) );
  17825. }
  17826. /**
  17827. * This method is intended for implementing the direct light term for
  17828. * rect area light nodes.
  17829. *
  17830. * @param {Object} input - The input data.
  17831. * @param {NodeBuilder} builder - The current node builder.
  17832. */
  17833. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  17834. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  17835. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  17836. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  17837. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  17838. const N = normalView;
  17839. const V = positionViewDirection;
  17840. const P = positionView.toVar();
  17841. const uv = LTC_Uv( { N, V, roughness } );
  17842. const t1 = ltc_1.sample( uv ).toVar();
  17843. const t2 = ltc_2.sample( uv ).toVar();
  17844. const mInv = mat3(
  17845. vec3( t1.x, 0, t1.y ),
  17846. vec3( 0, 1, 0 ),
  17847. vec3( t1.z, 0, t1.w )
  17848. ).toVar();
  17849. // LTC Fresnel Approximation by Stephen Hill
  17850. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  17851. const fresnel = specularColorBlended.mul( t2.x ).add( specularF90.sub( specularColorBlended ).mul( t2.y ) ).toVar();
  17852. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  17853. 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 } ) ) );
  17854. if ( this.clearcoat === true ) {
  17855. const Ncc = clearcoatNormalView;
  17856. const uvClearcoat = LTC_Uv( { N: Ncc, V, roughness: clearcoatRoughness } );
  17857. const t1Clearcoat = ltc_1.sample( uvClearcoat );
  17858. const t2Clearcoat = ltc_2.sample( uvClearcoat );
  17859. const mInvClearcoat = mat3(
  17860. vec3( t1Clearcoat.x, 0, t1Clearcoat.y ),
  17861. vec3( 0, 1, 0 ),
  17862. vec3( t1Clearcoat.z, 0, t1Clearcoat.w )
  17863. );
  17864. // LTC Fresnel Approximation for clearcoat
  17865. const fresnelClearcoat = clearcoatF0.mul( t2Clearcoat.x ).add( clearcoatF90.sub( clearcoatF0 ).mul( t2Clearcoat.y ) );
  17866. this.clearcoatSpecularDirect.addAssign( lightColor.mul( fresnelClearcoat ).mul( LTC_Evaluate( { N: Ncc, V, P, mInv: mInvClearcoat, p0, p1, p2, p3 } ) ) );
  17867. }
  17868. }
  17869. /**
  17870. * Implements the indirect lighting.
  17871. *
  17872. * @param {NodeBuilder} builder - The current node builder.
  17873. */
  17874. indirect( builder ) {
  17875. this.indirectDiffuse( builder );
  17876. this.indirectSpecular( builder );
  17877. this.ambientOcclusion( builder );
  17878. }
  17879. /**
  17880. * Implements the indirect diffuse term.
  17881. *
  17882. * @param {NodeBuilder} builder - The current node builder.
  17883. */
  17884. indirectDiffuse( builder ) {
  17885. const { irradiance, reflectedLight } = builder.context;
  17886. const diffuse = irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ).toVar();
  17887. if ( this.sheen === true ) {
  17888. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17889. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17890. diffuse.mulAssign( sheenEnergyComp );
  17891. }
  17892. reflectedLight.indirectDiffuse.addAssign( diffuse );
  17893. }
  17894. /**
  17895. * Implements the indirect specular term.
  17896. *
  17897. * @param {NodeBuilder} builder - The current node builder.
  17898. */
  17899. indirectSpecular( builder ) {
  17900. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  17901. if ( this.sheen === true ) {
  17902. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  17903. sheen,
  17904. IBLSheenBRDF( {
  17905. normal: normalView,
  17906. viewDir: positionViewDirection,
  17907. roughness: sheenRoughness
  17908. } )
  17909. ) );
  17910. }
  17911. if ( this.clearcoat === true ) {
  17912. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17913. const clearcoatEnv = EnvironmentBRDF( {
  17914. dotNV: dotNVcc,
  17915. specularColor: clearcoatF0,
  17916. specularF90: clearcoatF90,
  17917. roughness: clearcoatRoughness
  17918. } );
  17919. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  17920. }
  17921. // Both indirect specular and indirect diffuse light accumulate here
  17922. // Compute multiscattering separately for dielectric and metallic, then mix
  17923. const singleScatteringDielectric = vec3().toVar( 'singleScatteringDielectric' );
  17924. const multiScatteringDielectric = vec3().toVar( 'multiScatteringDielectric' );
  17925. const singleScatteringMetallic = vec3().toVar( 'singleScatteringMetallic' );
  17926. const multiScatteringMetallic = vec3().toVar( 'multiScatteringMetallic' );
  17927. this.computeMultiscattering( singleScatteringDielectric, multiScatteringDielectric, specularF90, specularColor, this.iridescenceF0Dielectric );
  17928. this.computeMultiscattering( singleScatteringMetallic, multiScatteringMetallic, specularF90, diffuseColor.rgb, this.iridescenceF0Metallic );
  17929. // Mix based on metalness
  17930. const singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, metalness );
  17931. const multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, metalness );
  17932. // Diffuse energy conservation uses dielectric path
  17933. const totalScatteringDielectric = singleScatteringDielectric.add( multiScatteringDielectric );
  17934. const diffuse = diffuseContribution.mul( totalScatteringDielectric.oneMinus() );
  17935. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  17936. const indirectSpecular = radiance.mul( singleScattering ).add( multiScattering.mul( cosineWeightedIrradiance ) ).toVar();
  17937. const indirectDiffuse = diffuse.mul( cosineWeightedIrradiance ).toVar();
  17938. if ( this.sheen === true ) {
  17939. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17940. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17941. indirectSpecular.mulAssign( sheenEnergyComp );
  17942. indirectDiffuse.mulAssign( sheenEnergyComp );
  17943. }
  17944. reflectedLight.indirectSpecular.addAssign( indirectSpecular );
  17945. reflectedLight.indirectDiffuse.addAssign( indirectDiffuse );
  17946. }
  17947. /**
  17948. * Implements the ambient occlusion term.
  17949. *
  17950. * @param {NodeBuilder} builder - The current node builder.
  17951. */
  17952. ambientOcclusion( builder ) {
  17953. const { ambientOcclusion, reflectedLight } = builder.context;
  17954. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17955. const aoNV = dotNV.add( ambientOcclusion );
  17956. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  17957. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  17958. if ( this.clearcoat === true ) {
  17959. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  17960. }
  17961. if ( this.sheen === true ) {
  17962. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  17963. }
  17964. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  17965. reflectedLight.indirectSpecular.mulAssign( aoNode );
  17966. }
  17967. /**
  17968. * Used for final lighting accumulations depending on the requested features.
  17969. *
  17970. * @param {NodeBuilder} builder - The current node builder.
  17971. */
  17972. finish( { context } ) {
  17973. const { outgoingLight } = context;
  17974. if ( this.clearcoat === true ) {
  17975. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17976. const Fcc = F_Schlick( {
  17977. dotVH: dotNVcc,
  17978. f0: clearcoatF0,
  17979. f90: clearcoatF90
  17980. } );
  17981. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  17982. outgoingLight.assign( clearcoatLight );
  17983. }
  17984. if ( this.sheen === true ) {
  17985. const sheenLight = outgoingLight.add( this.sheenSpecularDirect, this.sheenSpecularIndirect.mul( 1.0 / Math.PI ) );
  17986. outgoingLight.assign( sheenLight );
  17987. }
  17988. }
  17989. }
  17990. // These defines must match with PMREMGenerator
  17991. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  17992. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  17993. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  17994. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  17995. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  17996. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  17997. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  17998. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  17999. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  18000. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  18001. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  18002. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  18003. // These shader functions convert between the UV coordinates of a single face of
  18004. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  18005. // sampling a textureCube (not generally normalized ).
  18006. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  18007. const absDirection = vec3( abs( direction ) ).toVar();
  18008. const face = float( -1 ).toVar();
  18009. If( absDirection.x.greaterThan( absDirection.z ), () => {
  18010. If( absDirection.x.greaterThan( absDirection.y ), () => {
  18011. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  18012. } ).Else( () => {
  18013. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  18014. } );
  18015. } ).Else( () => {
  18016. If( absDirection.z.greaterThan( absDirection.y ), () => {
  18017. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  18018. } ).Else( () => {
  18019. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  18020. } );
  18021. } );
  18022. return face;
  18023. } ).setLayout( {
  18024. name: 'getFace',
  18025. type: 'float',
  18026. inputs: [
  18027. { name: 'direction', type: 'vec3' }
  18028. ]
  18029. } );
  18030. // RH coordinate system; PMREM face-indexing convention
  18031. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  18032. const uv = vec2().toVar();
  18033. If( face.equal( 0.0 ), () => {
  18034. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  18035. } ).ElseIf( face.equal( 1.0 ), () => {
  18036. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  18037. } ).ElseIf( face.equal( 2.0 ), () => {
  18038. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  18039. } ).ElseIf( face.equal( 3.0 ), () => {
  18040. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  18041. } ).ElseIf( face.equal( 4.0 ), () => {
  18042. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  18043. } ).Else( () => {
  18044. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  18045. } );
  18046. return mul( 0.5, uv.add( 1.0 ) );
  18047. } ).setLayout( {
  18048. name: 'getUV',
  18049. type: 'vec2',
  18050. inputs: [
  18051. { name: 'direction', type: 'vec3' },
  18052. { name: 'face', type: 'float' }
  18053. ]
  18054. } );
  18055. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  18056. const mip = float( 0.0 ).toVar();
  18057. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  18058. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  18059. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  18060. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  18061. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  18062. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  18063. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  18064. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  18065. } ).Else( () => {
  18066. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  18067. } );
  18068. return mip;
  18069. } ).setLayout( {
  18070. name: 'roughnessToMip',
  18071. type: 'float',
  18072. inputs: [
  18073. { name: 'roughness', type: 'float' }
  18074. ]
  18075. } );
  18076. // RH coordinate system; PMREM face-indexing convention
  18077. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  18078. const uv = uv_immutable.toVar();
  18079. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  18080. const direction = vec3( uv, 1.0 ).toVar();
  18081. If( face.equal( 0.0 ), () => {
  18082. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  18083. } ).ElseIf( face.equal( 1.0 ), () => {
  18084. direction.assign( direction.xzy );
  18085. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  18086. } ).ElseIf( face.equal( 2.0 ), () => {
  18087. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  18088. } ).ElseIf( face.equal( 3.0 ), () => {
  18089. direction.assign( direction.zyx );
  18090. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  18091. } ).ElseIf( face.equal( 4.0 ), () => {
  18092. direction.assign( direction.xzy );
  18093. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  18094. } ).ElseIf( face.equal( 5.0 ), () => {
  18095. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  18096. } );
  18097. return direction;
  18098. } ).setLayout( {
  18099. name: 'getDirection',
  18100. type: 'vec3',
  18101. inputs: [
  18102. { name: 'uv', type: 'vec2' },
  18103. { name: 'face', type: 'float' }
  18104. ]
  18105. } );
  18106. //
  18107. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  18108. const roughness = float( roughness_immutable );
  18109. const sampleDir = vec3( sampleDir_immutable );
  18110. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  18111. const mipF = fract( mip );
  18112. const mipInt = floor( mip );
  18113. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  18114. If( mipF.notEqual( 0.0 ), () => {
  18115. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  18116. color0.assign( mix( color0, color1, mipF ) );
  18117. } );
  18118. return color0;
  18119. } );
  18120. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  18121. const mipInt = float( mipInt_immutable ).toVar();
  18122. const direction = vec3( direction_immutable );
  18123. const face = float( getFace( direction ) ).toVar();
  18124. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  18125. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  18126. const faceSize = float( exp2( mipInt ) ).toVar();
  18127. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  18128. If( face.greaterThan( 2.0 ), () => {
  18129. uv.y.addAssign( faceSize );
  18130. face.subAssign( 3.0 );
  18131. } );
  18132. uv.x.addAssign( face.mul( faceSize ) );
  18133. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  18134. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  18135. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  18136. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  18137. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  18138. } );
  18139. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  18140. const cosTheta = cos( theta );
  18141. // Rodrigues' axis-angle rotation
  18142. const sampleDirection = outputDirection.mul( cosTheta )
  18143. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  18144. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  18145. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  18146. } );
  18147. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  18148. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  18149. If( axis.equal( vec3( 0.0 ) ), () => {
  18150. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  18151. } );
  18152. axis.assign( normalize( axis ) );
  18153. const gl_FragColor = vec3().toVar();
  18154. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  18155. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  18156. If( i.greaterThanEqual( samples ), () => {
  18157. Break();
  18158. } );
  18159. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  18160. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta: theta.mul( -1 ), axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  18161. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  18162. } );
  18163. return vec4( gl_FragColor, 1 );
  18164. } );
  18165. // GGX VNDF importance sampling functions
  18166. // Van der Corput radical inverse for generating quasi-random sequences
  18167. const radicalInverse_VdC = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  18168. const bits = uint( bits_immutable ).toVar();
  18169. bits.assign( bits.shiftLeft( uint( 16 ) ).bitOr( bits.shiftRight( uint( 16 ) ) ) );
  18170. bits.assign( bits.bitAnd( uint( 0x55555555 ) ).shiftLeft( uint( 1 ) ).bitOr( bits.bitAnd( uint( 0xAAAAAAAA ) ).shiftRight( uint( 1 ) ) ) );
  18171. bits.assign( bits.bitAnd( uint( 0x33333333 ) ).shiftLeft( uint( 2 ) ).bitOr( bits.bitAnd( uint( 0xCCCCCCCC ) ).shiftRight( uint( 2 ) ) ) );
  18172. bits.assign( bits.bitAnd( uint( 0x0F0F0F0F ) ).shiftLeft( uint( 4 ) ).bitOr( bits.bitAnd( uint( 0xF0F0F0F0 ) ).shiftRight( uint( 4 ) ) ) );
  18173. bits.assign( bits.bitAnd( uint( 0x00FF00FF ) ).shiftLeft( uint( 8 ) ).bitOr( bits.bitAnd( uint( 0xFF00FF00 ) ).shiftRight( uint( 8 ) ) ) );
  18174. return float( bits ).mul( 2.3283064365386963e-10 ); // / 0x100000000
  18175. } );
  18176. // Hammersley sequence for quasi-Monte Carlo sampling
  18177. const hammersley = /*@__PURE__*/ Fn( ( [ i, N ] ) => {
  18178. return vec2( float( i ).div( float( N ) ), radicalInverse_VdC( i ) );
  18179. } );
  18180. // GGX VNDF importance sampling (Eric Heitz 2018)
  18181. // "Sampling the GGX Distribution of Visible Normals"
  18182. // https://jcgt.org/published/0007/04/01/
  18183. const importanceSampleGGX_VNDF = /*@__PURE__*/ Fn( ( [ Xi, V, roughness ] ) => {
  18184. const alpha = roughness.mul( roughness ).toConst();
  18185. // Section 4.1: Orthonormal basis
  18186. const T1 = vec3( 1.0, 0.0, 0.0 ).toConst();
  18187. const T2 = cross( V, T1 ).toConst();
  18188. // Section 4.2: Parameterization of projected area
  18189. const r = sqrt( Xi.x ).toConst();
  18190. const phi = mul( 2.0, 3.14159265359 ).mul( Xi.y ).toConst();
  18191. const t1 = r.mul( cos( phi ) ).toConst();
  18192. const t2 = r.mul( sin( phi ) ).toVar();
  18193. const s = mul( 0.5, V.z.add( 1.0 ) ).toConst();
  18194. t2.assign( s.oneMinus().mul( sqrt( t1.mul( t1 ).oneMinus() ) ).add( s.mul( t2 ) ) );
  18195. // Section 4.3: Reprojection onto hemisphere
  18196. 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() ) ) ) );
  18197. // Section 3.4: Transform back to ellipsoid configuration
  18198. return normalize( vec3( alpha.mul( Nh.x ), alpha.mul( Nh.y ), max$1( 0.0, Nh.z ) ) );
  18199. } );
  18200. // GGX convolution using VNDF importance sampling
  18201. const ggxConvolution = /*@__PURE__*/ Fn( ( { roughness, mipInt, envMap, N_immutable, GGX_SAMPLES, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  18202. const N = vec3( N_immutable ).toVar();
  18203. const prefilteredColor = vec3( 0.0 ).toVar();
  18204. const totalWeight = float( 0.0 ).toVar();
  18205. // For very low roughness, just sample the environment directly
  18206. If( roughness.lessThan( 0.001 ), () => {
  18207. prefilteredColor.assign( bilinearCubeUV( envMap, N, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) );
  18208. } ).Else( () => {
  18209. // Tangent space basis for VNDF sampling
  18210. const up = select( abs( N.z ).lessThan( 0.999 ), vec3( 0.0, 0.0, 1.0 ), vec3( 1.0, 0.0, 0.0 ) );
  18211. const tangent = normalize( cross( up, N ) ).toVar();
  18212. const bitangent = cross( N, tangent ).toVar();
  18213. Loop( { start: uint( 0 ), end: GGX_SAMPLES }, ( { i } ) => {
  18214. const Xi = hammersley( i, GGX_SAMPLES );
  18215. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  18216. const H_tangent = importanceSampleGGX_VNDF( Xi, vec3( 0.0, 0.0, 1.0 ), roughness );
  18217. // Transform H back to world space
  18218. const H = normalize( tangent.mul( H_tangent.x ).add( bitangent.mul( H_tangent.y ) ).add( N.mul( H_tangent.z ) ) );
  18219. const L = normalize( H.mul( dot( N, H ).mul( 2.0 ) ).sub( N ) );
  18220. const NdotL = max$1( dot( N, L ), 0.0 );
  18221. If( NdotL.greaterThan( 0.0 ), () => {
  18222. // Sample environment at fixed mip level
  18223. // VNDF importance sampling handles the distribution filtering
  18224. const sampleColor = bilinearCubeUV( envMap, L, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  18225. // Weight by NdotL for the split-sum approximation
  18226. // VNDF PDF naturally accounts for the visible microfacet distribution
  18227. prefilteredColor.addAssign( sampleColor.mul( NdotL ) );
  18228. totalWeight.addAssign( NdotL );
  18229. } );
  18230. } );
  18231. If( totalWeight.greaterThan( 0.0 ), () => {
  18232. prefilteredColor.assign( prefilteredColor.div( totalWeight ) );
  18233. } );
  18234. } );
  18235. return vec4( prefilteredColor, 1.0 );
  18236. } );
  18237. const LOD_MIN = 4;
  18238. // The standard deviations (radians) associated with the extra mips.
  18239. // Used for scene blur in fromScene() method.
  18240. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  18241. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  18242. // samples and exit early, but not recompile the shader.
  18243. // Used for scene blur in fromScene() method.
  18244. const MAX_SAMPLES = 20;
  18245. // GGX VNDF importance sampling configuration
  18246. const GGX_SAMPLES = 512;
  18247. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  18248. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  18249. const _clearColor$2 = /*@__PURE__*/ new Color();
  18250. let _oldTarget = null;
  18251. let _oldActiveCubeFace = 0;
  18252. let _oldActiveMipmapLevel = 0;
  18253. const _origin = /*@__PURE__*/ new Vector3();
  18254. // maps blur materials to their uniforms dictionary
  18255. const _uniformsMap = new WeakMap();
  18256. // WebGPU Face indices
  18257. const _faceLib = [
  18258. 3, 1, 5,
  18259. 0, 4, 2
  18260. ];
  18261. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  18262. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  18263. /**
  18264. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  18265. * (PMREM) from a cubeMap environment texture. This allows different levels of
  18266. * blur to be quickly accessed based on material roughness. It is packed into a
  18267. * special CubeUV format that allows us to perform custom interpolation so that
  18268. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  18269. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  18270. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  18271. * higher roughness levels. In this way we maintain resolution to smoothly
  18272. * interpolate diffuse lighting while limiting sampling computation.
  18273. *
  18274. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  18275. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  18276. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  18277. * used in material rendering for physically-based image-based lighting.
  18278. */
  18279. class PMREMGenerator {
  18280. /**
  18281. * Constructs a new PMREM generator.
  18282. *
  18283. * @param {Renderer} renderer - The renderer.
  18284. */
  18285. constructor( renderer ) {
  18286. this._renderer = renderer;
  18287. this._pingPongRenderTarget = null;
  18288. this._lodMax = 0;
  18289. this._cubeSize = 0;
  18290. this._sizeLods = [];
  18291. this._sigmas = [];
  18292. this._lodMeshes = [];
  18293. this._blurMaterial = null;
  18294. this._ggxMaterial = null;
  18295. this._cubemapMaterial = null;
  18296. this._equirectMaterial = null;
  18297. this._backgroundBox = null;
  18298. }
  18299. get _hasInitialized() {
  18300. return this._renderer.hasInitialized();
  18301. }
  18302. /**
  18303. * Generates a PMREM from a supplied Scene, which can be faster than using an
  18304. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  18305. * in radians to be applied to the scene before PMREM generation. Optional near
  18306. * and far planes ensure the scene is rendered in its entirety.
  18307. *
  18308. * @param {Scene} scene - The scene to be captured.
  18309. * @param {number} [sigma=0] - The blur radius in radians.
  18310. * @param {number} [near=0.1] - The near plane distance.
  18311. * @param {number} [far=100] - The far plane distance.
  18312. * @param {Object} [options={}] - The configuration options.
  18313. * @param {number} [options.size=256] - The texture size of the PMREM.
  18314. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  18315. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  18316. * @return {RenderTarget} The resulting PMREM.
  18317. * @see {@link PMREMGenerator#fromScene}
  18318. */
  18319. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  18320. const {
  18321. size = 256,
  18322. position = _origin,
  18323. renderTarget = null,
  18324. } = options;
  18325. this._setSize( size );
  18326. if ( this._hasInitialized === false ) {
  18327. throw new Error( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Use "await renderer.init();" before using this method.' );
  18328. }
  18329. _oldTarget = this._renderer.getRenderTarget();
  18330. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  18331. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  18332. const cubeUVRenderTarget = renderTarget || this._allocateTarget( true );
  18333. this._init( cubeUVRenderTarget );
  18334. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  18335. if ( sigma > 0 ) {
  18336. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  18337. }
  18338. this._applyPMREM( cubeUVRenderTarget );
  18339. this._cleanup( cubeUVRenderTarget );
  18340. return cubeUVRenderTarget;
  18341. }
  18342. /**
  18343. * Generates a PMREM from a supplied Scene, which can be faster than using an
  18344. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  18345. * in radians to be applied to the scene before PMREM generation. Optional near
  18346. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  18347. * is placed at the origin).
  18348. *
  18349. * @deprecated
  18350. * @param {Scene} scene - The scene to be captured.
  18351. * @param {number} [sigma=0] - The blur radius in radians.
  18352. * @param {number} [near=0.1] - The near plane distance.
  18353. * @param {number} [far=100] - The far plane distance.
  18354. * @param {Object} [options={}] - The configuration options.
  18355. * @param {number} [options.size=256] - The texture size of the PMREM.
  18356. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  18357. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  18358. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  18359. * @see {@link PMREMGenerator#fromScene}
  18360. */
  18361. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  18362. warnOnce( 'PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  18363. await this._renderer.init();
  18364. return this.fromScene( scene, sigma, near, far, options );
  18365. }
  18366. /**
  18367. * Generates a PMREM from an equirectangular texture, which can be either LDR
  18368. * or HDR. The ideal input image size is 1k (1024 x 512), as this matches best
  18369. * with the 256 x 256 cubemap output. The minimum supported input image size
  18370. * is 64 x 32.
  18371. *
  18372. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  18373. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18374. * @return {RenderTarget} The resulting PMREM.
  18375. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  18376. */
  18377. fromEquirectangular( equirectangular, renderTarget = null ) {
  18378. if ( this._hasInitialized === false ) {
  18379. throw new Error( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Use "await renderer.init();" before using this method.' );
  18380. }
  18381. return this._fromTexture( equirectangular, renderTarget );
  18382. }
  18383. /**
  18384. * Generates a PMREM from an equirectangular texture, which can be either LDR
  18385. * or HDR. The ideal input image size is 1k (1024 x 512),
  18386. * as this matches best with the 256 x 256 cubemap output.
  18387. *
  18388. * @deprecated
  18389. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  18390. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18391. * @return {Promise<RenderTarget>} The resulting PMREM.
  18392. * @see {@link PMREMGenerator#fromEquirectangular}
  18393. */
  18394. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  18395. warnOnce( 'PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  18396. await this._renderer.init();
  18397. return this._fromTexture( equirectangular, renderTarget );
  18398. }
  18399. /**
  18400. * Generates a PMREM from an cubemap texture, which can be either LDR
  18401. * or HDR. The ideal input cube size is 256 x 256, as this matches best
  18402. * with the 256 x 256 cubemap output. The minimum supported input cube
  18403. * size is 16 x 16 per face.
  18404. *
  18405. * @param {Texture} cubemap - The cubemap texture to be converted.
  18406. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18407. * @return {RenderTarget} The resulting PMREM.
  18408. * @see {@link PMREMGenerator#fromCubemapAsync}
  18409. */
  18410. fromCubemap( cubemap, renderTarget = null ) {
  18411. if ( this._hasInitialized === false ) {
  18412. throw new Error( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Use "await renderer.init();" before using this method.' );
  18413. }
  18414. return this._fromTexture( cubemap, renderTarget );
  18415. }
  18416. /**
  18417. * Generates a PMREM from an cubemap texture, which can be either LDR
  18418. * or HDR. The ideal input cube size is 256 x 256,
  18419. * with the 256 x 256 cubemap output.
  18420. *
  18421. * @deprecated
  18422. * @param {Texture} cubemap - The cubemap texture to be converted.
  18423. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18424. * @return {Promise<RenderTarget>} The resulting PMREM.
  18425. * @see {@link PMREMGenerator#fromCubemap}
  18426. */
  18427. async fromCubemapAsync( cubemap, renderTarget = null ) {
  18428. warnOnce( 'PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  18429. await this._renderer.init();
  18430. return this._fromTexture( cubemap, renderTarget );
  18431. }
  18432. /**
  18433. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  18434. * your texture's network fetch for increased concurrency.
  18435. *
  18436. * @returns {Promise}
  18437. */
  18438. async compileCubemapShader() {
  18439. if ( this._cubemapMaterial === null ) {
  18440. this._cubemapMaterial = _getCubemapMaterial();
  18441. await this._compileMaterial( this._cubemapMaterial );
  18442. }
  18443. }
  18444. /**
  18445. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  18446. * your texture's network fetch for increased concurrency.
  18447. *
  18448. * @returns {Promise}
  18449. */
  18450. async compileEquirectangularShader() {
  18451. if ( this._equirectMaterial === null ) {
  18452. this._equirectMaterial = _getEquirectMaterial();
  18453. await this._compileMaterial( this._equirectMaterial );
  18454. }
  18455. }
  18456. /**
  18457. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  18458. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  18459. * one of them will cause any others to also become unusable.
  18460. */
  18461. dispose() {
  18462. this._dispose();
  18463. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  18464. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  18465. if ( this._backgroundBox !== null ) {
  18466. this._backgroundBox.geometry.dispose();
  18467. this._backgroundBox.material.dispose();
  18468. }
  18469. }
  18470. // private interface
  18471. _setSizeFromTexture( texture ) {
  18472. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  18473. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  18474. } else { // Equirectangular
  18475. this._setSize( texture.image.width / 4 );
  18476. }
  18477. }
  18478. _setSize( cubeSize ) {
  18479. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  18480. this._cubeSize = Math.pow( 2, this._lodMax );
  18481. }
  18482. _dispose() {
  18483. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  18484. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  18485. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  18486. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  18487. this._lodMeshes[ i ].geometry.dispose();
  18488. }
  18489. }
  18490. _cleanup( outputTarget ) {
  18491. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  18492. outputTarget.scissorTest = false;
  18493. this._setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  18494. }
  18495. _fromTexture( texture, renderTarget ) {
  18496. this._setSizeFromTexture( texture );
  18497. _oldTarget = this._renderer.getRenderTarget();
  18498. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  18499. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  18500. const cubeUVRenderTarget = renderTarget || this._allocateTarget( false );
  18501. this._init( cubeUVRenderTarget );
  18502. this._textureToCubeUV( texture, cubeUVRenderTarget );
  18503. this._applyPMREM( cubeUVRenderTarget );
  18504. this._cleanup( cubeUVRenderTarget );
  18505. return cubeUVRenderTarget;
  18506. }
  18507. _allocateTarget( depthBuffer ) {
  18508. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  18509. const height = 4 * this._cubeSize;
  18510. const cubeUVRenderTarget = _createRenderTarget( width, height, depthBuffer );
  18511. return cubeUVRenderTarget;
  18512. }
  18513. _init( renderTarget ) {
  18514. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  18515. if ( this._pingPongRenderTarget !== null ) {
  18516. this._dispose();
  18517. }
  18518. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  18519. const { _lodMax } = this;
  18520. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  18521. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  18522. this._ggxMaterial = _getGGXShader( _lodMax, renderTarget.width, renderTarget.height );
  18523. }
  18524. }
  18525. async _compileMaterial( material ) {
  18526. const mesh = new Mesh( new BufferGeometry(), material );
  18527. await this._renderer.compile( mesh, _flatCamera );
  18528. }
  18529. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  18530. const cubeCamera = _cubeCamera;
  18531. cubeCamera.near = near;
  18532. cubeCamera.far = far;
  18533. // px, py, pz, nx, ny, nz
  18534. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  18535. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  18536. const renderer = this._renderer;
  18537. const originalAutoClear = renderer.autoClear;
  18538. renderer.getClearColor( _clearColor$2 );
  18539. renderer.autoClear = false;
  18540. if ( this._backgroundBox === null ) {
  18541. this._backgroundBox = new Mesh(
  18542. new BoxGeometry(),
  18543. new MeshBasicMaterial( {
  18544. name: 'PMREM.Background',
  18545. side: BackSide,
  18546. depthWrite: false,
  18547. depthTest: false,
  18548. } )
  18549. );
  18550. }
  18551. const backgroundBox = this._backgroundBox;
  18552. const backgroundMaterial = backgroundBox.material;
  18553. let useSolidColor = false;
  18554. const background = scene.background;
  18555. if ( background ) {
  18556. if ( background.isColor ) {
  18557. backgroundMaterial.color.copy( background );
  18558. scene.background = null;
  18559. useSolidColor = true;
  18560. }
  18561. } else {
  18562. backgroundMaterial.color.copy( _clearColor$2 );
  18563. useSolidColor = true;
  18564. }
  18565. renderer.setRenderTarget( cubeUVRenderTarget );
  18566. renderer.clear();
  18567. if ( useSolidColor ) {
  18568. renderer.render( backgroundBox, cubeCamera );
  18569. }
  18570. for ( let i = 0; i < 6; i ++ ) {
  18571. const col = i % 3;
  18572. if ( col === 0 ) {
  18573. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18574. cubeCamera.position.set( position.x, position.y, position.z );
  18575. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  18576. } else if ( col === 1 ) {
  18577. cubeCamera.up.set( 0, 0, upSign[ i ] );
  18578. cubeCamera.position.set( position.x, position.y, position.z );
  18579. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  18580. } else {
  18581. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18582. cubeCamera.position.set( position.x, position.y, position.z );
  18583. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  18584. }
  18585. const size = this._cubeSize;
  18586. this._setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  18587. renderer.render( scene, cubeCamera );
  18588. }
  18589. renderer.autoClear = originalAutoClear;
  18590. scene.background = background;
  18591. }
  18592. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  18593. const renderer = this._renderer;
  18594. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  18595. if ( isCubeTexture ) {
  18596. if ( this._cubemapMaterial === null ) {
  18597. this._cubemapMaterial = _getCubemapMaterial( texture );
  18598. }
  18599. } else {
  18600. if ( this._equirectMaterial === null ) {
  18601. this._equirectMaterial = _getEquirectMaterial( texture );
  18602. }
  18603. }
  18604. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  18605. material.fragmentNode.value = texture;
  18606. const mesh = this._lodMeshes[ 0 ];
  18607. mesh.material = material;
  18608. const size = this._cubeSize;
  18609. this._setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  18610. renderer.setRenderTarget( cubeUVRenderTarget );
  18611. renderer.render( mesh, _flatCamera );
  18612. }
  18613. _applyPMREM( cubeUVRenderTarget ) {
  18614. const renderer = this._renderer;
  18615. const autoClear = renderer.autoClear;
  18616. renderer.autoClear = false;
  18617. const n = this._lodMeshes.length;
  18618. // Use GGX VNDF importance sampling
  18619. for ( let i = 1; i < n; i ++ ) {
  18620. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  18621. }
  18622. renderer.autoClear = autoClear;
  18623. }
  18624. /**
  18625. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  18626. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  18627. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  18628. * applies incremental roughness filtering to avoid over-blurring.
  18629. *
  18630. * @private
  18631. * @param {RenderTarget} cubeUVRenderTarget
  18632. * @param {number} lodIn - Source LOD level to read from
  18633. * @param {number} lodOut - Target LOD level to write to
  18634. */
  18635. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  18636. const renderer = this._renderer;
  18637. const pingPongRenderTarget = this._pingPongRenderTarget;
  18638. const ggxMaterial = this._ggxMaterial;
  18639. const ggxMesh = this._lodMeshes[ lodOut ];
  18640. ggxMesh.material = ggxMaterial;
  18641. const ggxUniforms = _uniformsMap.get( ggxMaterial );
  18642. // Calculate incremental roughness between LOD levels
  18643. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  18644. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  18645. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  18646. // Apply blur strength mapping for better quality across the roughness range
  18647. const blurStrength = 0.0 + targetRoughness * 1.25;
  18648. const adjustedRoughness = incrementalRoughness * blurStrength;
  18649. // Calculate viewport position based on output LOD level
  18650. const { _lodMax } = this;
  18651. const outputSize = this._sizeLods[ lodOut ];
  18652. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18653. const y = 4 * ( this._cubeSize - outputSize );
  18654. // Read from previous LOD with incremental roughness
  18655. cubeUVRenderTarget.texture.frame = ( cubeUVRenderTarget.texture.frame || 0 ) + 1;
  18656. ggxUniforms.envMap.value = cubeUVRenderTarget.texture;
  18657. ggxUniforms.roughness.value = adjustedRoughness;
  18658. ggxUniforms.mipInt.value = _lodMax - lodIn; // Sample from input LOD
  18659. this._setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18660. renderer.setRenderTarget( pingPongRenderTarget );
  18661. renderer.render( ggxMesh, _flatCamera );
  18662. // Copy from pingPong back to cubeUV (simple direct copy)
  18663. pingPongRenderTarget.texture.frame = ( pingPongRenderTarget.texture.frame || 0 ) + 1;
  18664. ggxUniforms.envMap.value = pingPongRenderTarget.texture;
  18665. ggxUniforms.roughness.value = 0.0; // Direct copy
  18666. ggxUniforms.mipInt.value = _lodMax - lodOut; // Read from the level we just wrote
  18667. this._setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18668. renderer.setRenderTarget( cubeUVRenderTarget );
  18669. renderer.render( ggxMesh, _flatCamera );
  18670. }
  18671. /**
  18672. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  18673. * vertically and horizontally, but this breaks down on a cube. Here we apply
  18674. * the blur latitudinally (around the poles), and then longitudinally (towards
  18675. * the poles) to approximate the orthogonally-separable blur. It is least
  18676. * accurate at the poles, but still does a decent job.
  18677. *
  18678. * Used for initial scene blur in fromScene() method when sigma > 0.
  18679. *
  18680. * @private
  18681. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  18682. * @param {number} lodIn - The input level-of-detail.
  18683. * @param {number} lodOut - The output level-of-detail.
  18684. * @param {number} sigma - The blur radius in radians.
  18685. * @param {Vector3} [poleAxis] - The pole axis.
  18686. */
  18687. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  18688. const pingPongRenderTarget = this._pingPongRenderTarget;
  18689. this._halfBlur(
  18690. cubeUVRenderTarget,
  18691. pingPongRenderTarget,
  18692. lodIn,
  18693. lodOut,
  18694. sigma,
  18695. 'latitudinal',
  18696. poleAxis );
  18697. this._halfBlur(
  18698. pingPongRenderTarget,
  18699. cubeUVRenderTarget,
  18700. lodOut,
  18701. lodOut,
  18702. sigma,
  18703. 'longitudinal',
  18704. poleAxis );
  18705. }
  18706. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  18707. const renderer = this._renderer;
  18708. const blurMaterial = this._blurMaterial;
  18709. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  18710. error( 'blur direction must be either latitudinal or longitudinal!' );
  18711. }
  18712. // Number of standard deviations at which to cut off the discrete approximation.
  18713. const STANDARD_DEVIATIONS = 3;
  18714. const blurMesh = this._lodMeshes[ lodOut ];
  18715. blurMesh.material = blurMaterial;
  18716. const blurUniforms = _uniformsMap.get( blurMaterial );
  18717. const pixels = this._sizeLods[ lodIn ] - 1;
  18718. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  18719. const sigmaPixels = sigmaRadians / radiansPerPixel;
  18720. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  18721. if ( samples > MAX_SAMPLES ) {
  18722. warn( `sigmaRadians, ${
  18723. sigmaRadians}, is too large and will clip, as it requested ${
  18724. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  18725. }
  18726. const weights = [];
  18727. let sum = 0;
  18728. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  18729. const x = i / sigmaPixels;
  18730. const weight = Math.exp( - x * x / 2 );
  18731. weights.push( weight );
  18732. if ( i === 0 ) {
  18733. sum += weight;
  18734. } else if ( i < samples ) {
  18735. sum += 2 * weight;
  18736. }
  18737. }
  18738. for ( let i = 0; i < weights.length; i ++ ) {
  18739. weights[ i ] = weights[ i ] / sum;
  18740. }
  18741. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  18742. blurUniforms.envMap.value = targetIn.texture;
  18743. blurUniforms.samples.value = samples;
  18744. blurUniforms.weights.array = weights;
  18745. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  18746. if ( poleAxis ) {
  18747. blurUniforms.poleAxis.value = poleAxis;
  18748. }
  18749. const { _lodMax } = this;
  18750. blurUniforms.dTheta.value = radiansPerPixel;
  18751. blurUniforms.mipInt.value = _lodMax - lodIn;
  18752. const outputSize = this._sizeLods[ lodOut ];
  18753. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18754. const y = 4 * ( this._cubeSize - outputSize );
  18755. this._setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  18756. renderer.setRenderTarget( targetOut );
  18757. renderer.render( blurMesh, _flatCamera );
  18758. }
  18759. _setViewport( target, x, y, width, height ) {
  18760. if ( this._renderer.isWebGLRenderer ) {
  18761. target.viewport.set( x, target.height - height - y, width, height );
  18762. target.scissor.set( x, target.height - height - y, width, height );
  18763. } else {
  18764. target.viewport.set( x, y, width, height );
  18765. target.scissor.set( x, y, width, height );
  18766. }
  18767. }
  18768. }
  18769. function _createPlanes( lodMax ) {
  18770. const sizeLods = [];
  18771. const sigmas = [];
  18772. const lodMeshes = [];
  18773. let lod = lodMax;
  18774. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  18775. for ( let i = 0; i < totalLods; i ++ ) {
  18776. const sizeLod = Math.pow( 2, lod );
  18777. sizeLods.push( sizeLod );
  18778. let sigma = 1.0 / sizeLod;
  18779. if ( i > lodMax - LOD_MIN ) {
  18780. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  18781. } else if ( i === 0 ) {
  18782. sigma = 0;
  18783. }
  18784. sigmas.push( sigma );
  18785. const texelSize = 1.0 / ( sizeLod - 2 );
  18786. const min = - texelSize;
  18787. const max = 1 + texelSize;
  18788. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  18789. const cubeFaces = 6;
  18790. const vertices = 6;
  18791. const positionSize = 3;
  18792. const uvSize = 2;
  18793. const faceIndexSize = 1;
  18794. const position = new Float32Array( positionSize * vertices * cubeFaces );
  18795. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  18796. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  18797. for ( let face = 0; face < cubeFaces; face ++ ) {
  18798. const x = ( face % 3 ) * 2 / 3 - 1;
  18799. const y = face > 2 ? 0 : -1;
  18800. const coordinates = [
  18801. x, y, 0,
  18802. x + 2 / 3, y, 0,
  18803. x + 2 / 3, y + 1, 0,
  18804. x, y, 0,
  18805. x + 2 / 3, y + 1, 0,
  18806. x, y + 1, 0
  18807. ];
  18808. const faceIdx = _faceLib[ face ];
  18809. position.set( coordinates, positionSize * vertices * faceIdx );
  18810. uv.set( uv1, uvSize * vertices * faceIdx );
  18811. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  18812. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  18813. }
  18814. const planes = new BufferGeometry();
  18815. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  18816. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  18817. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  18818. lodMeshes.push( new Mesh( planes, null ) );
  18819. if ( lod > LOD_MIN ) {
  18820. lod --;
  18821. }
  18822. }
  18823. return { lodMeshes, sizeLods, sigmas };
  18824. }
  18825. function _createRenderTarget( width, height, depthBuffer ) {
  18826. const params = {
  18827. magFilter: LinearFilter,
  18828. minFilter: LinearFilter,
  18829. generateMipmaps: false,
  18830. type: HalfFloatType,
  18831. format: RGBAFormat,
  18832. colorSpace: LinearSRGBColorSpace,
  18833. depthBuffer
  18834. };
  18835. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  18836. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  18837. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  18838. cubeUVRenderTarget.texture.isPMREMTexture = true;
  18839. cubeUVRenderTarget.scissorTest = true;
  18840. return cubeUVRenderTarget;
  18841. }
  18842. function _getMaterial( type ) {
  18843. const material = new NodeMaterial();
  18844. material.depthTest = false;
  18845. material.depthWrite = false;
  18846. material.blending = NoBlending;
  18847. material.name = `PMREM_${ type }`;
  18848. return material;
  18849. }
  18850. function _getBlurShader( lodMax, width, height ) {
  18851. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  18852. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  18853. const dTheta = uniform( 0 );
  18854. const n = float( MAX_SAMPLES );
  18855. const latitudinal = uniform( 0 ); // false, bool
  18856. const samples = uniform( 1 ); // int
  18857. const envMap = texture();
  18858. const mipInt = uniform( 0 ); // int
  18859. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18860. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18861. const CUBEUV_MAX_MIP = float( lodMax );
  18862. const materialUniforms = {
  18863. n,
  18864. latitudinal,
  18865. weights,
  18866. poleAxis,
  18867. outputDirection: _outputDirection,
  18868. dTheta,
  18869. samples,
  18870. envMap,
  18871. mipInt,
  18872. CUBEUV_TEXEL_WIDTH,
  18873. CUBEUV_TEXEL_HEIGHT,
  18874. CUBEUV_MAX_MIP
  18875. };
  18876. const material = _getMaterial( 'blur' );
  18877. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  18878. _uniformsMap.set( material, materialUniforms );
  18879. return material;
  18880. }
  18881. function _getGGXShader( lodMax, width, height ) {
  18882. const envMap = texture();
  18883. const roughness = uniform( 0 );
  18884. const mipInt = uniform( 0 );
  18885. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18886. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18887. const CUBEUV_MAX_MIP = float( lodMax );
  18888. const materialUniforms = {
  18889. envMap,
  18890. roughness,
  18891. mipInt,
  18892. CUBEUV_TEXEL_WIDTH,
  18893. CUBEUV_TEXEL_HEIGHT,
  18894. CUBEUV_MAX_MIP
  18895. };
  18896. const material = _getMaterial( 'ggx' );
  18897. material.fragmentNode = ggxConvolution( {
  18898. ...materialUniforms,
  18899. N_immutable: _outputDirection,
  18900. GGX_SAMPLES: uint( GGX_SAMPLES )
  18901. } );
  18902. _uniformsMap.set( material, materialUniforms );
  18903. return material;
  18904. }
  18905. function _getCubemapMaterial( envTexture ) {
  18906. const material = _getMaterial( 'cubemap' );
  18907. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  18908. return material;
  18909. }
  18910. function _getEquirectMaterial( envTexture ) {
  18911. const material = _getMaterial( 'equirect' );
  18912. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  18913. return material;
  18914. }
  18915. const _cache = new WeakMap();
  18916. /**
  18917. * Generates the cubeUV size based on the given image height.
  18918. *
  18919. * @private
  18920. * @param {number} imageHeight - The image height.
  18921. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  18922. */
  18923. function _generateCubeUVSize( imageHeight ) {
  18924. const maxMip = Math.log2( imageHeight ) - 2;
  18925. const texelHeight = 1.0 / imageHeight;
  18926. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  18927. return { texelWidth, texelHeight, maxMip };
  18928. }
  18929. /**
  18930. * Generates a PMREM from the given texture.
  18931. *
  18932. * @private
  18933. * @param {Texture} texture - The texture to create the PMREM for.
  18934. * @param {Renderer} renderer - The renderer.
  18935. * @param {PMREMGenerator} generator - The PMREM generator.
  18936. * @return {?Texture} The PMREM.
  18937. */
  18938. function _getPMREMFromTexture( texture, renderer, generator ) {
  18939. const cache = _getCache( renderer );
  18940. let cacheTexture = cache.get( texture );
  18941. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  18942. if ( pmremVersion !== texture.pmremVersion ) {
  18943. const image = texture.image;
  18944. if ( texture.isCubeTexture ) {
  18945. if ( isCubeMapReady( image ) ) {
  18946. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  18947. } else {
  18948. return null;
  18949. }
  18950. } else {
  18951. if ( isEquirectangularMapReady( image ) ) {
  18952. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  18953. } else {
  18954. return null;
  18955. }
  18956. }
  18957. cacheTexture.pmremVersion = texture.pmremVersion;
  18958. cache.set( texture, cacheTexture );
  18959. }
  18960. return cacheTexture.texture;
  18961. }
  18962. /**
  18963. * Returns a cache that stores generated PMREMs for the respective textures.
  18964. * A cache must be maintained per renderer since PMREMs are render target textures
  18965. * which can't be shared across render contexts.
  18966. *
  18967. * @private
  18968. * @param {Renderer} renderer - The renderer.
  18969. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  18970. */
  18971. function _getCache( renderer ) {
  18972. let rendererCache = _cache.get( renderer );
  18973. if ( rendererCache === undefined ) {
  18974. rendererCache = new WeakMap();
  18975. _cache.set( renderer, rendererCache );
  18976. }
  18977. return rendererCache;
  18978. }
  18979. /**
  18980. * This node represents a PMREM which is a special type of preprocessed
  18981. * environment map intended for PBR materials.
  18982. *
  18983. * ```js
  18984. * const material = new MeshStandardNodeMaterial();
  18985. * material.envNode = pmremTexture( envMap );
  18986. * ```
  18987. *
  18988. * @augments TempNode
  18989. */
  18990. class PMREMNode extends TempNode {
  18991. static get type() {
  18992. return 'PMREMNode';
  18993. }
  18994. /**
  18995. * Constructs a new function overloading node.
  18996. *
  18997. * @param {Texture} value - The input texture.
  18998. * @param {Node<vec2>} [uvNode=null] - The uv node.
  18999. * @param {Node<float>} [levelNode=null] - The level node.
  19000. */
  19001. constructor( value, uvNode = null, levelNode = null ) {
  19002. super( 'vec3' );
  19003. /**
  19004. * Reference to the input texture.
  19005. *
  19006. * @private
  19007. * @type {Texture}
  19008. */
  19009. this._value = value;
  19010. /**
  19011. * Reference to the generated PMREM.
  19012. *
  19013. * @private
  19014. * @type {Texture | null}
  19015. * @default null
  19016. */
  19017. this._pmrem = null;
  19018. /**
  19019. * The uv node.
  19020. *
  19021. * @type {Node<vec2>}
  19022. */
  19023. this.uvNode = uvNode;
  19024. /**
  19025. * The level node.
  19026. *
  19027. * @type {Node<float>}
  19028. */
  19029. this.levelNode = levelNode;
  19030. /**
  19031. * Reference to a PMREM generator.
  19032. *
  19033. * @private
  19034. * @type {?PMREMGenerator}
  19035. * @default null
  19036. */
  19037. this._generator = null;
  19038. const defaultTexture = new Texture();
  19039. defaultTexture.isRenderTargetTexture = true;
  19040. /**
  19041. * The texture node holding the generated PMREM.
  19042. *
  19043. * @private
  19044. * @type {TextureNode}
  19045. */
  19046. this._texture = texture( defaultTexture );
  19047. /**
  19048. * A uniform representing the PMREM's width.
  19049. *
  19050. * @private
  19051. * @type {UniformNode<float>}
  19052. */
  19053. this._width = uniform( 0 );
  19054. /**
  19055. * A uniform representing the PMREM's height.
  19056. *
  19057. * @private
  19058. * @type {UniformNode<float>}
  19059. */
  19060. this._height = uniform( 0 );
  19061. /**
  19062. * A uniform representing the PMREM's max Mip.
  19063. *
  19064. * @private
  19065. * @type {UniformNode<float>}
  19066. */
  19067. this._maxMip = uniform( 0 );
  19068. /**
  19069. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  19070. *
  19071. * @type {string}
  19072. * @default 'render'
  19073. */
  19074. this.updateBeforeType = NodeUpdateType.RENDER;
  19075. }
  19076. set value( value ) {
  19077. this._value = value;
  19078. this._pmrem = null;
  19079. }
  19080. /**
  19081. * The node's texture value.
  19082. *
  19083. * @type {Texture}
  19084. */
  19085. get value() {
  19086. return this._value;
  19087. }
  19088. /**
  19089. * Uses the given PMREM texture to update internal values.
  19090. *
  19091. * @param {Texture} texture - The PMREM texture.
  19092. */
  19093. updateFromTexture( texture ) {
  19094. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  19095. this._texture.value = texture;
  19096. this._width.value = cubeUVSize.texelWidth;
  19097. this._height.value = cubeUVSize.texelHeight;
  19098. this._maxMip.value = cubeUVSize.maxMip;
  19099. }
  19100. updateBefore( frame ) {
  19101. let pmrem = this._pmrem;
  19102. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  19103. const texture = this._value;
  19104. if ( pmremVersion !== texture.pmremVersion ) {
  19105. if ( texture.isPMREMTexture === true || texture.mapping === CubeUVReflectionMapping ) {
  19106. pmrem = texture;
  19107. } else {
  19108. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  19109. }
  19110. if ( pmrem !== null ) {
  19111. this._pmrem = pmrem;
  19112. this.updateFromTexture( pmrem );
  19113. }
  19114. }
  19115. }
  19116. setup( builder ) {
  19117. if ( this._generator === null ) {
  19118. this._generator = new PMREMGenerator( builder.renderer );
  19119. }
  19120. this.updateBefore( builder );
  19121. //
  19122. let uvNode = this.uvNode;
  19123. if ( uvNode === null && builder.context.getUV ) {
  19124. uvNode = builder.context.getUV( this, builder );
  19125. }
  19126. //
  19127. // PMREMGenerator renders into a render target with inverted Y, so its output needs the Y
  19128. // flip on sampling. Externally authored PMREMs follow the standard convention and don't.
  19129. uvNode = this._pmrem.isRenderTargetTexture
  19130. ? materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) )
  19131. : materialEnvRotation.mul( uvNode );
  19132. //
  19133. let levelNode = this.levelNode;
  19134. if ( levelNode === null && builder.context.getTextureLevel ) {
  19135. levelNode = builder.context.getTextureLevel( this );
  19136. }
  19137. //
  19138. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  19139. }
  19140. dispose() {
  19141. super.dispose();
  19142. if ( this._generator !== null ) this._generator.dispose();
  19143. }
  19144. }
  19145. /**
  19146. * Returns `true` if the given cube map image has been fully loaded.
  19147. *
  19148. * @private
  19149. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  19150. * @return {boolean} Whether the given cube map is ready or not.
  19151. */
  19152. function isCubeMapReady( image ) {
  19153. if ( image === null || image === undefined ) return false;
  19154. let count = 0;
  19155. const length = 6;
  19156. for ( let i = 0; i < length; i ++ ) {
  19157. if ( image[ i ] !== undefined ) count ++;
  19158. }
  19159. return count === length;
  19160. }
  19161. /**
  19162. * Returns `true` if the given equirectangular image has been fully loaded.
  19163. *
  19164. * @private
  19165. * @param {(Image|Object)} image - The equirectangular image.
  19166. * @return {boolean} Whether the given cube map is ready or not.
  19167. */
  19168. function isEquirectangularMapReady( image ) {
  19169. if ( image === null || image === undefined ) return false;
  19170. return image.height > 0;
  19171. }
  19172. /**
  19173. * TSL function for creating a PMREM node.
  19174. *
  19175. * @tsl
  19176. * @function
  19177. * @param {Texture} value - The input texture.
  19178. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  19179. * @param {?Node<float>} [levelNode=null] - The level node.
  19180. * @returns {PMREMNode}
  19181. */
  19182. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  19183. const _rendererCache = new WeakMap();
  19184. /**
  19185. * Represents a physical model for Image-based lighting (IBL). The environment
  19186. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  19187. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  19188. *
  19189. * @augments LightingNode
  19190. */
  19191. class EnvironmentNode extends LightingNode {
  19192. static get type() {
  19193. return 'EnvironmentNode';
  19194. }
  19195. /**
  19196. * Constructs a new environment node.
  19197. *
  19198. * @param {Node} [envNode=null] - A node representing the environment.
  19199. */
  19200. constructor( envNode = null ) {
  19201. super();
  19202. /**
  19203. * A node representing the environment.
  19204. *
  19205. * @type {?Node}
  19206. * @default null
  19207. */
  19208. this.envNode = envNode;
  19209. }
  19210. setup( builder ) {
  19211. const { material } = builder;
  19212. let envNode = this.envNode;
  19213. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  19214. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  19215. const cache = this._getPMREMNodeCache( builder.renderer );
  19216. let cacheEnvNode = cache.get( value );
  19217. if ( cacheEnvNode === undefined ) {
  19218. cacheEnvNode = pmremTexture( value );
  19219. cache.set( value, cacheEnvNode );
  19220. }
  19221. envNode = cacheEnvNode;
  19222. }
  19223. //
  19224. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  19225. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  19226. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  19227. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  19228. const isolateRadiance = isolate( radiance );
  19229. const isolateIrradiance = isolate( irradiance );
  19230. //
  19231. builder.context.radiance.addAssign( isolateRadiance );
  19232. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  19233. //
  19234. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  19235. if ( clearcoatRadiance ) {
  19236. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  19237. const isolateClearcoatRadiance = isolate( clearcoatRadianceContext );
  19238. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  19239. }
  19240. }
  19241. /**
  19242. * Returns the PMREM node cache of the current renderer.
  19243. *
  19244. * @private
  19245. * @param {Renderer} renderer - The current renderer.
  19246. * @return {WeakMap} The node cache.
  19247. */
  19248. _getPMREMNodeCache( renderer ) {
  19249. let pmremCache = _rendererCache.get( renderer );
  19250. if ( pmremCache === undefined ) {
  19251. pmremCache = new WeakMap();
  19252. _rendererCache.set( renderer, pmremCache );
  19253. }
  19254. return pmremCache;
  19255. }
  19256. }
  19257. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  19258. let reflectVec = null;
  19259. return {
  19260. getUV: () => {
  19261. if ( reflectVec === null ) {
  19262. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  19263. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  19264. reflectVec = pow4( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  19265. reflectVec = reflectVec.transformDirection( cameraWorldMatrix );
  19266. }
  19267. return reflectVec;
  19268. },
  19269. getTextureLevel: () => {
  19270. return roughnessNode;
  19271. }
  19272. };
  19273. };
  19274. const createIrradianceContext = ( normalWorldNode ) => {
  19275. return {
  19276. getUV: () => {
  19277. return normalWorldNode;
  19278. },
  19279. getTextureLevel: () => {
  19280. return float( 1.0 );
  19281. }
  19282. };
  19283. };
  19284. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  19285. /**
  19286. * Node material version of {@link MeshStandardMaterial}.
  19287. *
  19288. * @augments NodeMaterial
  19289. */
  19290. class MeshStandardNodeMaterial extends NodeMaterial {
  19291. static get type() {
  19292. return 'MeshStandardNodeMaterial';
  19293. }
  19294. /**
  19295. * Constructs a new mesh standard node material.
  19296. *
  19297. * @param {Object} [parameters] - The configuration parameter.
  19298. */
  19299. constructor( parameters ) {
  19300. super();
  19301. /**
  19302. * This flag can be used for type testing.
  19303. *
  19304. * @type {boolean}
  19305. * @readonly
  19306. * @default true
  19307. */
  19308. this.isMeshStandardNodeMaterial = true;
  19309. /**
  19310. * Set to `true` because standard materials react on lights.
  19311. *
  19312. * @type {boolean}
  19313. * @default true
  19314. */
  19315. this.lights = true;
  19316. /**
  19317. * The emissive color of standard materials is by default inferred from the `emissive`,
  19318. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  19319. * overwrite the default and define the emissive color with a node instead.
  19320. *
  19321. * If you don't want to overwrite the emissive color but modify the existing
  19322. * value instead, use {@link materialEmissive}.
  19323. *
  19324. * @type {?Node<vec3>}
  19325. * @default null
  19326. */
  19327. this.emissiveNode = null;
  19328. /**
  19329. * The metalness of standard materials is by default inferred from the `metalness`,
  19330. * and `metalnessMap` properties. This node property allows to
  19331. * overwrite the default and define the metalness with a node instead.
  19332. *
  19333. * If you don't want to overwrite the metalness but modify the existing
  19334. * value instead, use {@link materialMetalness}.
  19335. *
  19336. * @type {?Node<float>}
  19337. * @default null
  19338. */
  19339. this.metalnessNode = null;
  19340. /**
  19341. * The roughness of standard materials is by default inferred from the `roughness`,
  19342. * and `roughnessMap` properties. This node property allows to
  19343. * overwrite the default and define the roughness with a node instead.
  19344. *
  19345. * If you don't want to overwrite the roughness but modify the existing
  19346. * value instead, use {@link materialRoughness}.
  19347. *
  19348. * @type {?Node<float>}
  19349. * @default null
  19350. */
  19351. this.roughnessNode = null;
  19352. this.setDefaultValues( _defaultValues$6 );
  19353. this.setValues( parameters );
  19354. }
  19355. /**
  19356. * Overwritten since this type of material uses {@link EnvironmentNode}
  19357. * to implement the PBR (PMREM based) environment mapping. Besides, the
  19358. * method honors `Scene.environment`.
  19359. *
  19360. * @param {NodeBuilder} builder - The current node builder.
  19361. * @return {?EnvironmentNode<vec3>} The environment node.
  19362. */
  19363. setupEnvironment( builder ) {
  19364. let envNode = super.setupEnvironment( builder );
  19365. if ( envNode === null && builder.environmentNode ) {
  19366. envNode = builder.environmentNode;
  19367. }
  19368. return envNode ? new EnvironmentNode( envNode ) : null;
  19369. }
  19370. /**
  19371. * Setups the lighting model.
  19372. *
  19373. * @return {PhysicalLightingModel} The lighting model.
  19374. */
  19375. setupLightingModel( /*builder*/ ) {
  19376. return new PhysicalLightingModel();
  19377. }
  19378. /**
  19379. * Setups the specular related node variables.
  19380. */
  19381. setupSpecular() {
  19382. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  19383. specularColor.assign( vec3( 0.04 ) );
  19384. specularColorBlended.assign( specularColorNode );
  19385. specularF90.assign( 1.0 );
  19386. }
  19387. /**
  19388. * Setups the standard specific node variables.
  19389. *
  19390. * @param {NodeBuilder} builder - The current node builder.
  19391. */
  19392. setupVariants() {
  19393. // METALNESS
  19394. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  19395. metalness.assign( metalnessNode );
  19396. // ROUGHNESS
  19397. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  19398. roughnessNode = getRoughness( { roughness: roughnessNode } );
  19399. roughness.assign( roughnessNode );
  19400. // SPECULAR COLOR
  19401. this.setupSpecular();
  19402. // DIFFUSE COLOR
  19403. diffuseContribution.assign( diffuseColor.rgb.mul( metalnessNode.oneMinus() ) );
  19404. }
  19405. }
  19406. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  19407. /**
  19408. * Node material version of {@link MeshPhysicalMaterial}.
  19409. *
  19410. * @augments MeshStandardNodeMaterial
  19411. */
  19412. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  19413. static get type() {
  19414. return 'MeshPhysicalNodeMaterial';
  19415. }
  19416. /**
  19417. * Constructs a new mesh physical node material.
  19418. *
  19419. * @param {Object} [parameters] - The configuration parameter.
  19420. */
  19421. constructor( parameters ) {
  19422. super();
  19423. /**
  19424. * This flag can be used for type testing.
  19425. *
  19426. * @type {boolean}
  19427. * @readonly
  19428. * @default true
  19429. */
  19430. this.isMeshPhysicalNodeMaterial = true;
  19431. /**
  19432. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  19433. * and `clearcoatMap` properties. This node property allows to overwrite the default
  19434. * and define the clearcoat with a node instead.
  19435. *
  19436. * If you don't want to overwrite the clearcoat but modify the existing
  19437. * value instead, use {@link materialClearcoat}.
  19438. *
  19439. * @type {?Node<float>}
  19440. * @default null
  19441. */
  19442. this.clearcoatNode = null;
  19443. /**
  19444. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  19445. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  19446. * and define the clearcoat roughness with a node instead.
  19447. *
  19448. * If you don't want to overwrite the clearcoat roughness but modify the existing
  19449. * value instead, use {@link materialClearcoatRoughness}.
  19450. *
  19451. * @type {?Node<float>}
  19452. * @default null
  19453. */
  19454. this.clearcoatRoughnessNode = null;
  19455. /**
  19456. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  19457. * property. This node property allows to overwrite the default
  19458. * and define the clearcoat normal with a node instead.
  19459. *
  19460. * If you don't want to overwrite the clearcoat normal but modify the existing
  19461. * value instead, use {@link materialClearcoatNormal}.
  19462. *
  19463. * @type {?Node<vec3>}
  19464. * @default null
  19465. */
  19466. this.clearcoatNormalNode = null;
  19467. /**
  19468. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  19469. * and `sheenColorMap` properties. This node property allows to overwrite the default
  19470. * and define the sheen with a node instead.
  19471. *
  19472. * If you don't want to overwrite the sheen but modify the existing
  19473. * value instead, use {@link materialSheen}.
  19474. *
  19475. * @type {?Node<vec3>}
  19476. * @default null
  19477. */
  19478. this.sheenNode = null;
  19479. /**
  19480. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  19481. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  19482. * and define the sheen roughness with a node instead.
  19483. *
  19484. * If you don't want to overwrite the sheen roughness but modify the existing
  19485. * value instead, use {@link materialSheenRoughness}.
  19486. *
  19487. * @type {?Node<float>}
  19488. * @default null
  19489. */
  19490. this.sheenRoughnessNode = null;
  19491. /**
  19492. * The iridescence of physical materials is by default inferred from the `iridescence`
  19493. * property. This node property allows to overwrite the default
  19494. * and define the iridescence with a node instead.
  19495. *
  19496. * If you don't want to overwrite the iridescence but modify the existing
  19497. * value instead, use {@link materialIridescence}.
  19498. *
  19499. * @type {?Node<float>}
  19500. * @default null
  19501. */
  19502. this.iridescenceNode = null;
  19503. /**
  19504. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  19505. * property. This node property allows to overwrite the default
  19506. * and define the iridescence IOR with a node instead.
  19507. *
  19508. * If you don't want to overwrite the iridescence IOR but modify the existing
  19509. * value instead, use {@link materialIridescenceIOR}.
  19510. *
  19511. * @type {?Node<float>}
  19512. * @default null
  19513. */
  19514. this.iridescenceIORNode = null;
  19515. /**
  19516. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  19517. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  19518. * and define the iridescence thickness with a node instead.
  19519. *
  19520. * If you don't want to overwrite the iridescence thickness but modify the existing
  19521. * value instead, use {@link materialIridescenceThickness}.
  19522. *
  19523. * @type {?Node<float>}
  19524. * @default null
  19525. */
  19526. this.iridescenceThicknessNode = null;
  19527. /**
  19528. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  19529. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  19530. * and define the specular intensity with a node instead.
  19531. *
  19532. * If you don't want to overwrite the specular intensity but modify the existing
  19533. * value instead, use {@link materialSpecularIntensity}.
  19534. *
  19535. * @type {?Node<float>}
  19536. * @default null
  19537. */
  19538. this.specularIntensityNode = null;
  19539. /**
  19540. * The specular color of physical materials is by default inferred from the `specularColor`
  19541. * and `specularColorMap` properties. This node property allows to overwrite the default
  19542. * and define the specular color with a node instead.
  19543. *
  19544. * If you don't want to overwrite the specular color but modify the existing
  19545. * value instead, use {@link materialSpecularColor}.
  19546. *
  19547. * @type {?Node<vec3>}
  19548. * @default null
  19549. */
  19550. this.specularColorNode = null;
  19551. /**
  19552. * The ior of physical materials is by default inferred from the `ior`
  19553. * property. This node property allows to overwrite the default
  19554. * and define the ior with a node instead.
  19555. *
  19556. * If you don't want to overwrite the ior but modify the existing
  19557. * value instead, use {@link materialIOR}.
  19558. *
  19559. * @type {?Node<float>}
  19560. * @default null
  19561. */
  19562. this.iorNode = null;
  19563. /**
  19564. * The transmission of physical materials is by default inferred from the `transmission` and
  19565. * `transmissionMap` properties. This node property allows to overwrite the default
  19566. * and define the transmission with a node instead.
  19567. *
  19568. * If you don't want to overwrite the transmission but modify the existing
  19569. * value instead, use {@link materialTransmission}.
  19570. *
  19571. * @type {?Node<float>}
  19572. * @default null
  19573. */
  19574. this.transmissionNode = null;
  19575. /**
  19576. * The thickness of physical materials is by default inferred from the `thickness` and
  19577. * `thicknessMap` properties. This node property allows to overwrite the default
  19578. * and define the thickness with a node instead.
  19579. *
  19580. * If you don't want to overwrite the thickness but modify the existing
  19581. * value instead, use {@link materialThickness}.
  19582. *
  19583. * @type {?Node<float>}
  19584. * @default null
  19585. */
  19586. this.thicknessNode = null;
  19587. /**
  19588. * The attenuation distance of physical materials is by default inferred from the
  19589. * `attenuationDistance` property. This node property allows to overwrite the default
  19590. * and define the attenuation distance with a node instead.
  19591. *
  19592. * If you don't want to overwrite the attenuation distance but modify the existing
  19593. * value instead, use {@link materialAttenuationDistance}.
  19594. *
  19595. * @type {?Node<float>}
  19596. * @default null
  19597. */
  19598. this.attenuationDistanceNode = null;
  19599. /**
  19600. * The attenuation color of physical materials is by default inferred from the
  19601. * `attenuationColor` property. This node property allows to overwrite the default
  19602. * and define the attenuation color with a node instead.
  19603. *
  19604. * If you don't want to overwrite the attenuation color but modify the existing
  19605. * value instead, use {@link materialAttenuationColor}.
  19606. *
  19607. * @type {?Node<vec3>}
  19608. * @default null
  19609. */
  19610. this.attenuationColorNode = null;
  19611. /**
  19612. * The dispersion of physical materials is by default inferred from the
  19613. * `dispersion` property. This node property allows to overwrite the default
  19614. * and define the dispersion with a node instead.
  19615. *
  19616. * If you don't want to overwrite the dispersion but modify the existing
  19617. * value instead, use {@link materialDispersion}.
  19618. *
  19619. * @type {?Node<float>}
  19620. * @default null
  19621. */
  19622. this.dispersionNode = null;
  19623. /**
  19624. * The anisotropy of physical materials is by default inferred from the
  19625. * `anisotropy` property. This node property allows to overwrite the default
  19626. * and define the anisotropy with a node instead.
  19627. *
  19628. * If you don't want to overwrite the anisotropy but modify the existing
  19629. * value instead, use {@link materialAnisotropy}.
  19630. *
  19631. * @type {?Node<float>}
  19632. * @default null
  19633. */
  19634. this.anisotropyNode = null;
  19635. this.setDefaultValues( _defaultValues$5 );
  19636. this.setValues( parameters );
  19637. }
  19638. /**
  19639. * Whether the lighting model should use clearcoat or not.
  19640. *
  19641. * @type {boolean}
  19642. * @default true
  19643. */
  19644. get useClearcoat() {
  19645. return this.clearcoat > 0 || this.clearcoatNode !== null;
  19646. }
  19647. /**
  19648. * Whether the lighting model should use iridescence or not.
  19649. *
  19650. * @type {boolean}
  19651. * @default true
  19652. */
  19653. get useIridescence() {
  19654. return this.iridescence > 0 || this.iridescenceNode !== null;
  19655. }
  19656. /**
  19657. * Whether the lighting model should use sheen or not.
  19658. *
  19659. * @type {boolean}
  19660. * @default true
  19661. */
  19662. get useSheen() {
  19663. return this.sheen > 0 || this.sheenNode !== null;
  19664. }
  19665. /**
  19666. * Whether the lighting model should use anisotropy or not.
  19667. *
  19668. * @type {boolean}
  19669. * @default true
  19670. */
  19671. get useAnisotropy() {
  19672. return this.anisotropy > 0 || this.anisotropyNode !== null;
  19673. }
  19674. /**
  19675. * Whether the lighting model should use transmission or not.
  19676. *
  19677. * @type {boolean}
  19678. * @default true
  19679. */
  19680. get useTransmission() {
  19681. return this.transmission > 0 || this.transmissionNode !== null;
  19682. }
  19683. /**
  19684. * Whether the lighting model should use dispersion or not.
  19685. *
  19686. * @type {boolean}
  19687. * @default true
  19688. */
  19689. get useDispersion() {
  19690. return this.dispersion > 0 || this.dispersionNode !== null;
  19691. }
  19692. /**
  19693. * Setups the specular related node variables.
  19694. */
  19695. setupSpecular() {
  19696. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  19697. ior.assign( iorNode );
  19698. specularColor.assign( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ) );
  19699. specularColorBlended.assign( mix( specularColor, diffuseColor.rgb, metalness ) );
  19700. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  19701. }
  19702. /**
  19703. * Setups the lighting model.
  19704. *
  19705. * @return {PhysicalLightingModel} The lighting model.
  19706. */
  19707. setupLightingModel( /*builder*/ ) {
  19708. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  19709. }
  19710. /**
  19711. * Setups the physical specific node variables.
  19712. *
  19713. * @param {NodeBuilder} builder - The current node builder.
  19714. */
  19715. setupVariants( builder ) {
  19716. super.setupVariants( builder );
  19717. // CLEARCOAT
  19718. if ( this.useClearcoat ) {
  19719. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  19720. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  19721. clearcoat.assign( clearcoatNode );
  19722. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  19723. }
  19724. // SHEEN
  19725. if ( this.useSheen ) {
  19726. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  19727. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  19728. sheen.assign( sheenNode );
  19729. sheenRoughness.assign( sheenRoughnessNode );
  19730. }
  19731. // IRIDESCENCE
  19732. if ( this.useIridescence ) {
  19733. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  19734. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  19735. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  19736. iridescence.assign( iridescenceNode );
  19737. iridescenceIOR.assign( iridescenceIORNode );
  19738. iridescenceThickness.assign( iridescenceThicknessNode );
  19739. }
  19740. // ANISOTROPY
  19741. if ( this.useAnisotropy ) {
  19742. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  19743. anisotropy.assign( anisotropyV.length() );
  19744. If( anisotropy.equal( 0.0 ), () => {
  19745. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  19746. } ).Else( () => {
  19747. anisotropyV.divAssign( vec2( anisotropy ) );
  19748. anisotropy.assign( anisotropy.saturate() );
  19749. } );
  19750. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  19751. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  19752. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  19753. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  19754. }
  19755. // TRANSMISSION
  19756. if ( this.useTransmission ) {
  19757. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  19758. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  19759. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  19760. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  19761. transmission.assign( transmissionNode );
  19762. thickness.assign( thicknessNode );
  19763. attenuationDistance.assign( attenuationDistanceNode );
  19764. attenuationColor.assign( attenuationColorNode );
  19765. if ( this.useDispersion ) {
  19766. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  19767. dispersion.assign( dispersionNode );
  19768. }
  19769. }
  19770. }
  19771. /**
  19772. * Setups the clearcoat normal node.
  19773. *
  19774. * @return {Node<vec3>} The clearcoat normal.
  19775. */
  19776. setupClearcoatNormal() {
  19777. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  19778. }
  19779. setup( builder ) {
  19780. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  19781. super.setup( builder );
  19782. }
  19783. }
  19784. /**
  19785. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  19786. *
  19787. * @augments PhysicalLightingModel
  19788. */
  19789. class SSSLightingModel extends PhysicalLightingModel {
  19790. /**
  19791. * Constructs a new physical lighting model.
  19792. *
  19793. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  19794. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  19795. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  19796. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  19797. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  19798. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  19799. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  19800. */
  19801. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  19802. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  19803. /**
  19804. * Whether the lighting model should use SSS or not.
  19805. *
  19806. * @type {boolean}
  19807. * @default false
  19808. */
  19809. this.useSSS = sss;
  19810. }
  19811. /**
  19812. * Extends the default implementation with a SSS term.
  19813. *
  19814. * 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/)
  19815. *
  19816. * @param {Object} input - The input data.
  19817. * @param {NodeBuilder} builder - The current node builder.
  19818. */
  19819. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19820. if ( this.useSSS === true ) {
  19821. const material = builder.material;
  19822. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  19823. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  19824. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  19825. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  19826. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  19827. }
  19828. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  19829. }
  19830. }
  19831. /**
  19832. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  19833. * that implements a Subsurface scattering (SSS) term.
  19834. *
  19835. * @augments MeshPhysicalNodeMaterial
  19836. */
  19837. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  19838. static get type() {
  19839. return 'MeshSSSNodeMaterial';
  19840. }
  19841. /**
  19842. * Constructs a new mesh SSS node material.
  19843. *
  19844. * @param {Object} [parameters] - The configuration parameter.
  19845. */
  19846. constructor( parameters ) {
  19847. super( parameters );
  19848. /**
  19849. * Represents the thickness color.
  19850. *
  19851. * @type {?Node<vec3>}
  19852. * @default null
  19853. */
  19854. this.thicknessColorNode = null;
  19855. /**
  19856. * Represents the distortion factor.
  19857. *
  19858. * @type {?Node<float>}
  19859. */
  19860. this.thicknessDistortionNode = float( 0.1 );
  19861. /**
  19862. * Represents the thickness ambient factor.
  19863. *
  19864. * @type {?Node<float>}
  19865. */
  19866. this.thicknessAmbientNode = float( 0.0 );
  19867. /**
  19868. * Represents the thickness attenuation.
  19869. *
  19870. * @type {?Node<float>}
  19871. */
  19872. this.thicknessAttenuationNode = float( .1 );
  19873. /**
  19874. * Represents the thickness power.
  19875. *
  19876. * @type {?Node<float>}
  19877. */
  19878. this.thicknessPowerNode = float( 2.0 );
  19879. /**
  19880. * Represents the thickness scale.
  19881. *
  19882. * @type {?Node<float>}
  19883. */
  19884. this.thicknessScaleNode = float( 10.0 );
  19885. }
  19886. /**
  19887. * Whether the lighting model should use SSS or not.
  19888. *
  19889. * @type {boolean}
  19890. * @default true
  19891. */
  19892. get useSSS() {
  19893. return this.thicknessColorNode !== null;
  19894. }
  19895. /**
  19896. * Setups the lighting model.
  19897. *
  19898. * @return {SSSLightingModel} The lighting model.
  19899. */
  19900. setupLightingModel( /*builder*/ ) {
  19901. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  19902. }
  19903. }
  19904. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  19905. // dotNL will be from -1.0 to 1.0
  19906. const dotNL = normal.dot( lightDirection );
  19907. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  19908. if ( builder.material.gradientMap ) {
  19909. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  19910. return vec3( gradientMap.r );
  19911. } else {
  19912. const fw = coord.fwidth().mul( 0.5 );
  19913. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  19914. }
  19915. } );
  19916. /**
  19917. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  19918. *
  19919. * @augments LightingModel
  19920. */
  19921. class ToonLightingModel extends LightingModel {
  19922. /**
  19923. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  19924. * reduced to a small number of discrete shades to create a comic-like, flat look.
  19925. *
  19926. * @param {Object} lightData - The light data.
  19927. * @param {NodeBuilder} builder - The current node builder.
  19928. */
  19929. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19930. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  19931. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  19932. }
  19933. /**
  19934. * Implements the indirect lighting.
  19935. *
  19936. * @param {NodeBuilder} builder - The current node builder.
  19937. */
  19938. indirect( builder ) {
  19939. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  19940. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  19941. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  19942. }
  19943. }
  19944. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  19945. /**
  19946. * Node material version of {@link MeshToonMaterial}.
  19947. *
  19948. * @augments NodeMaterial
  19949. */
  19950. class MeshToonNodeMaterial extends NodeMaterial {
  19951. static get type() {
  19952. return 'MeshToonNodeMaterial';
  19953. }
  19954. /**
  19955. * Constructs a new mesh toon node material.
  19956. *
  19957. * @param {Object} [parameters] - The configuration parameter.
  19958. */
  19959. constructor( parameters ) {
  19960. super();
  19961. /**
  19962. * This flag can be used for type testing.
  19963. *
  19964. * @type {boolean}
  19965. * @readonly
  19966. * @default true
  19967. */
  19968. this.isMeshToonNodeMaterial = true;
  19969. /**
  19970. * Set to `true` because toon materials react on lights.
  19971. *
  19972. * @type {boolean}
  19973. * @default true
  19974. */
  19975. this.lights = true;
  19976. this.setDefaultValues( _defaultValues$4 );
  19977. this.setValues( parameters );
  19978. }
  19979. /**
  19980. * Setups the lighting model.
  19981. *
  19982. * @return {ToonLightingModel} The lighting model.
  19983. */
  19984. setupLightingModel( /*builder*/ ) {
  19985. return new ToonLightingModel();
  19986. }
  19987. }
  19988. /**
  19989. * TSL function for creating a matcap uv node.
  19990. *
  19991. * Can be used to compute texture coordinates for projecting a
  19992. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  19993. *
  19994. * @tsl
  19995. * @function
  19996. * @returns {Node<vec2>} The matcap UV coordinates.
  19997. */
  19998. const matcapUV = /*@__PURE__*/ Fn( () => {
  19999. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  20000. const y = positionViewDirection.cross( x );
  20001. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  20002. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  20003. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  20004. /**
  20005. * Node material version of {@link MeshMatcapMaterial}.
  20006. *
  20007. * @augments NodeMaterial
  20008. */
  20009. class MeshMatcapNodeMaterial extends NodeMaterial {
  20010. static get type() {
  20011. return 'MeshMatcapNodeMaterial';
  20012. }
  20013. /**
  20014. * Constructs a new mesh normal node material.
  20015. *
  20016. * @param {Object} [parameters] - The configuration parameter.
  20017. */
  20018. constructor( parameters ) {
  20019. super();
  20020. /**
  20021. * This flag can be used for type testing.
  20022. *
  20023. * @type {boolean}
  20024. * @readonly
  20025. * @default true
  20026. */
  20027. this.isMeshMatcapNodeMaterial = true;
  20028. this.setDefaultValues( _defaultValues$3 );
  20029. this.setValues( parameters );
  20030. }
  20031. /**
  20032. * Setups the matcap specific node variables.
  20033. *
  20034. * @param {NodeBuilder} builder - The current node builder.
  20035. */
  20036. setupVariants( builder ) {
  20037. const uv = matcapUV;
  20038. let matcapColor;
  20039. if ( builder.material.matcap ) {
  20040. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  20041. } else {
  20042. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  20043. }
  20044. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  20045. }
  20046. }
  20047. /**
  20048. * Applies a rotation to the given position node.
  20049. *
  20050. * @augments TempNode
  20051. */
  20052. class RotateNode extends TempNode {
  20053. static get type() {
  20054. return 'RotateNode';
  20055. }
  20056. /**
  20057. * Constructs a new rotate node.
  20058. *
  20059. * @param {Node} positionNode - The position node.
  20060. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  20061. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  20062. */
  20063. constructor( positionNode, rotationNode ) {
  20064. super();
  20065. /**
  20066. * The position node.
  20067. *
  20068. * @type {Node}
  20069. */
  20070. this.positionNode = positionNode;
  20071. /**
  20072. * Represents the rotation that is applied to the position node.
  20073. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  20074. *
  20075. * @type {Node}
  20076. */
  20077. this.rotationNode = rotationNode;
  20078. }
  20079. /**
  20080. * The type of the {@link RotateNode#positionNode} defines the node's type.
  20081. *
  20082. * @param {NodeBuilder} builder - The current node builder.
  20083. * @return {string} The node's type.
  20084. */
  20085. generateNodeType( builder ) {
  20086. return this.positionNode.getNodeType( builder );
  20087. }
  20088. setup( builder ) {
  20089. const { rotationNode, positionNode } = this;
  20090. const nodeType = this.getNodeType( builder );
  20091. if ( nodeType === 'vec2' ) {
  20092. const cosAngle = rotationNode.cos();
  20093. const sinAngle = rotationNode.sin();
  20094. const rotationMatrix = mat2(
  20095. cosAngle, sinAngle,
  20096. sinAngle.negate(), cosAngle
  20097. );
  20098. return rotationMatrix.mul( positionNode );
  20099. } else {
  20100. const rotation = rotationNode;
  20101. 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 ) );
  20102. 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 ) );
  20103. 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 ) );
  20104. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  20105. }
  20106. }
  20107. }
  20108. /**
  20109. * TSL function for creating a rotate node.
  20110. *
  20111. * @tsl
  20112. * @function
  20113. * @param {Node} positionNode - The position node.
  20114. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  20115. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  20116. * @returns {RotateNode}
  20117. */
  20118. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  20119. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  20120. /**
  20121. * Node material version of {@link SpriteMaterial}.
  20122. *
  20123. * @augments NodeMaterial
  20124. */
  20125. class SpriteNodeMaterial extends NodeMaterial {
  20126. static get type() {
  20127. return 'SpriteNodeMaterial';
  20128. }
  20129. /**
  20130. * Constructs a new sprite node material.
  20131. *
  20132. * @param {Object} [parameters] - The configuration parameter.
  20133. */
  20134. constructor( parameters ) {
  20135. super();
  20136. /**
  20137. * This flag can be used for type testing.
  20138. *
  20139. * @type {boolean}
  20140. * @readonly
  20141. * @default true
  20142. */
  20143. this.isSpriteNodeMaterial = true;
  20144. this._useSizeAttenuation = true;
  20145. /**
  20146. * This property makes it possible to define the position of the sprite with a
  20147. * node. That can be useful when the material is used with instanced rendering
  20148. * and node data are defined with an instanced attribute node:
  20149. * ```js
  20150. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  20151. * material.positionNode = instancedBufferAttribute( positionAttribute );
  20152. * ```
  20153. * Another possibility is to compute the instanced data with a compute shader:
  20154. * ```js
  20155. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  20156. * particleMaterial.positionNode = positionBuffer.toAttribute();
  20157. * ```
  20158. *
  20159. * @type {?Node<vec2>}
  20160. * @default null
  20161. */
  20162. this.positionNode = null;
  20163. /**
  20164. * The rotation of sprite materials is by default inferred from the `rotation`,
  20165. * property. This node property allows to overwrite the default and define
  20166. * the rotation with a node instead.
  20167. *
  20168. * If you don't want to overwrite the rotation but modify the existing
  20169. * value instead, use {@link materialRotation}.
  20170. *
  20171. * @type {?Node<float>}
  20172. * @default null
  20173. */
  20174. this.rotationNode = null;
  20175. /**
  20176. * This node property provides an additional way to scale sprites next to
  20177. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  20178. * is multiplied with the scale value of this node in the vertex shader.
  20179. *
  20180. * @type {?Node<vec2>}
  20181. * @default null
  20182. */
  20183. this.scaleNode = null;
  20184. /**
  20185. * In Sprites, the transparent property is enabled by default.
  20186. *
  20187. * @type {boolean}
  20188. * @default true
  20189. */
  20190. this.transparent = true;
  20191. this.setDefaultValues( _defaultValues$2 );
  20192. this.setValues( parameters );
  20193. }
  20194. /**
  20195. * Setups the position node in view space. This method implements
  20196. * the sprite specific vertex shader.
  20197. *
  20198. * @param {NodeBuilder} builder - The current node builder.
  20199. * @return {Node<vec3>} The position in view space.
  20200. */
  20201. setupPositionView( builder ) {
  20202. const { object, camera } = builder;
  20203. const { positionNode, rotationNode, scaleNode, sizeAttenuation } = this;
  20204. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  20205. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  20206. if ( scaleNode !== null ) {
  20207. scale = scale.mul( vec2( scaleNode ) );
  20208. }
  20209. if ( camera.isPerspectiveCamera && sizeAttenuation === false ) {
  20210. scale = scale.mul( mvPosition.z.negate() );
  20211. }
  20212. let alignedPosition = positionGeometry.xy;
  20213. if ( object.center && object.center.isVector2 === true ) {
  20214. const center = reference$1( 'center', 'vec2', object );
  20215. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  20216. }
  20217. alignedPosition = alignedPosition.mul( scale );
  20218. const rotation = float( rotationNode || materialRotation );
  20219. const rotatedPosition = rotate( alignedPosition, rotation );
  20220. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  20221. }
  20222. /**
  20223. * Whether to use size attenuation or not.
  20224. *
  20225. * @type {boolean}
  20226. * @default true
  20227. */
  20228. get sizeAttenuation() {
  20229. return this._useSizeAttenuation;
  20230. }
  20231. set sizeAttenuation( value ) {
  20232. if ( this._useSizeAttenuation !== value ) {
  20233. this._useSizeAttenuation = value;
  20234. this.needsUpdate = true;
  20235. }
  20236. }
  20237. }
  20238. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  20239. const _size$4 = /*@__PURE__*/ new Vector2();
  20240. /**
  20241. * Node material version of {@link PointsMaterial}.
  20242. *
  20243. * This material can be used in two ways:
  20244. *
  20245. * - By rendering point primitives with {@link Points}. Since WebGPU only supports point primitives
  20246. * with a pixel size of `1`, it's not possible to define a size.
  20247. *
  20248. * ```js
  20249. * const pointCloud = new THREE.Points( geometry, new THREE.PointsNodeMaterial() );
  20250. * ```
  20251. *
  20252. * - By rendering point primitives with {@link Sprites}. In this case, size is honored,
  20253. * see {@link PointsNodeMaterial#sizeNode}.
  20254. *
  20255. * ```js
  20256. * const instancedPoints = new THREE.Sprite( new THREE.PointsNodeMaterial( { positionNode: instancedBufferAttribute( positionAttribute ) } ) );
  20257. * ```
  20258. *
  20259. * @augments SpriteNodeMaterial
  20260. */
  20261. class PointsNodeMaterial extends SpriteNodeMaterial {
  20262. static get type() {
  20263. return 'PointsNodeMaterial';
  20264. }
  20265. /**
  20266. * Constructs a new points node material.
  20267. *
  20268. * @param {Object} [parameters] - The configuration parameter.
  20269. */
  20270. constructor( parameters ) {
  20271. super();
  20272. /**
  20273. * This node property provides an additional way to set the point size.
  20274. *
  20275. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  20276. * this node has no effect when the material is used with {@link Points} and a WebGPU
  20277. * backend. If an application wants to render points with a size larger than 1 pixel,
  20278. * the material should be used with {@link Sprite} and instancing.
  20279. *
  20280. * @type {?Node<vec2>}
  20281. * @default null
  20282. */
  20283. this.sizeNode = null;
  20284. /**
  20285. * This flag can be used for type testing.
  20286. *
  20287. * @type {boolean}
  20288. * @readonly
  20289. * @default true
  20290. */
  20291. this.isPointsNodeMaterial = true;
  20292. this.setDefaultValues( _defaultValues$1 );
  20293. this.setValues( parameters );
  20294. }
  20295. setupPositionView() {
  20296. const { positionNode } = this;
  20297. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  20298. }
  20299. setupVertexSprite( builder ) {
  20300. const { material, camera } = builder;
  20301. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  20302. let mvp = super.setupVertex( builder );
  20303. // skip further processing if the material is not a node material
  20304. if ( material.isNodeMaterial !== true ) {
  20305. return mvp;
  20306. }
  20307. // point size
  20308. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  20309. pointSize = pointSize.mul( screenDPR );
  20310. // size attenuation
  20311. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  20312. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  20313. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  20314. }
  20315. // scale
  20316. if ( scaleNode && scaleNode.isNode ) {
  20317. pointSize = pointSize.mul( vec2( scaleNode ) );
  20318. }
  20319. // compute offset
  20320. let offset = positionGeometry.xy;
  20321. // apply rotation
  20322. if ( rotationNode && rotationNode.isNode ) {
  20323. const rotation = float( rotationNode );
  20324. offset = rotate( offset, rotation );
  20325. }
  20326. // account for point size
  20327. offset = offset.mul( pointSize );
  20328. // scale by viewport size
  20329. offset = offset.div( viewportSize.div( 2 ) );
  20330. // compensate for the perspective divide
  20331. offset = offset.mul( mvp.w );
  20332. // add offset
  20333. mvp = mvp.add( vec4( offset, 0, 0 ) );
  20334. return mvp;
  20335. }
  20336. setupVertex( builder ) {
  20337. if ( builder.object.isPoints ) {
  20338. return super.setupVertex( builder );
  20339. } else {
  20340. return this.setupVertexSprite( builder );
  20341. }
  20342. }
  20343. /**
  20344. * Whether alpha to coverage should be used or not.
  20345. *
  20346. * @type {boolean}
  20347. * @default true
  20348. */
  20349. get alphaToCoverage() {
  20350. return this._useAlphaToCoverage;
  20351. }
  20352. set alphaToCoverage( value ) {
  20353. if ( this._useAlphaToCoverage !== value ) {
  20354. this._useAlphaToCoverage = value;
  20355. this.needsUpdate = true;
  20356. }
  20357. }
  20358. }
  20359. const scale = /*@__PURE__*/ uniform( 1 ).onFrameUpdate( function ( { renderer } ) {
  20360. const size = renderer.getSize( _size$4 ); // logical units
  20361. this.value = 0.5 * size.y;
  20362. } );
  20363. /**
  20364. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  20365. *
  20366. * @augments LightingModel
  20367. */
  20368. class ShadowMaskModel extends LightingModel {
  20369. /**
  20370. * Constructs a new shadow mask model.
  20371. */
  20372. constructor() {
  20373. super();
  20374. /**
  20375. * The shadow mask node.
  20376. *
  20377. * @type {Node}
  20378. */
  20379. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  20380. }
  20381. /**
  20382. * Only used to save the shadow mask.
  20383. *
  20384. * @param {Object} input - The input data.
  20385. */
  20386. direct( { lightNode } ) {
  20387. if ( lightNode.shadowNode !== null ) {
  20388. this.shadowNode.mulAssign( lightNode.shadowNode );
  20389. }
  20390. }
  20391. /**
  20392. * Uses the shadow mask to produce the final color.
  20393. *
  20394. * @param {NodeBuilder} builder - The current node builder.
  20395. */
  20396. finish( { context } ) {
  20397. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  20398. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  20399. }
  20400. }
  20401. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  20402. /**
  20403. * Node material version of {@link ShadowMaterial}.
  20404. *
  20405. * @augments NodeMaterial
  20406. */
  20407. class ShadowNodeMaterial extends NodeMaterial {
  20408. static get type() {
  20409. return 'ShadowNodeMaterial';
  20410. }
  20411. /**
  20412. * Constructs a new shadow node material.
  20413. *
  20414. * @param {Object} [parameters] - The configuration parameter.
  20415. */
  20416. constructor( parameters ) {
  20417. super();
  20418. /**
  20419. * This flag can be used for type testing.
  20420. *
  20421. * @type {boolean}
  20422. * @readonly
  20423. * @default true
  20424. */
  20425. this.isShadowNodeMaterial = true;
  20426. /**
  20427. * Set to `true` because so it's possible to implement
  20428. * the shadow mask effect.
  20429. *
  20430. * @type {boolean}
  20431. * @default true
  20432. */
  20433. this.lights = true;
  20434. /**
  20435. * Overwritten since shadow materials are transparent
  20436. * by default.
  20437. *
  20438. * @type {boolean}
  20439. * @default true
  20440. */
  20441. this.transparent = true;
  20442. this.setDefaultValues( _defaultValues );
  20443. this.setValues( parameters );
  20444. }
  20445. /**
  20446. * Setups the lighting model.
  20447. *
  20448. * @return {ShadowMaskModel} The lighting model.
  20449. */
  20450. setupLightingModel( /*builder*/ ) {
  20451. return new ShadowMaskModel();
  20452. }
  20453. }
  20454. const scatteringDensity = property( 'vec3' );
  20455. const linearDepthRay = property( 'vec3' );
  20456. const outgoingRayLight = property( 'vec3' );
  20457. /**
  20458. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  20459. * This model calculates the scattering and transmittance of light through a volumetric medium.
  20460. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  20461. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  20462. *
  20463. * @augments LightingModel
  20464. */
  20465. class VolumetricLightingModel extends LightingModel {
  20466. constructor() {
  20467. super();
  20468. }
  20469. start( builder ) {
  20470. const { material } = builder;
  20471. const startPos = property( 'vec3' );
  20472. const endPos = property( 'vec3' );
  20473. // This approach dynamically changes the direction of the ray,
  20474. // 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.
  20475. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  20476. startPos.assign( cameraPosition );
  20477. endPos.assign( positionWorld );
  20478. } ).Else( () => {
  20479. startPos.assign( positionWorld );
  20480. endPos.assign( cameraPosition );
  20481. } );
  20482. //
  20483. const viewVector = endPos.sub( startPos );
  20484. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  20485. const stepSize = viewVector.length().div( steps ).toVar();
  20486. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  20487. const distTravelled = float( 0.0 ).toVar();
  20488. const transmittance = vec3( 1 ).toVar();
  20489. if ( material.offsetNode ) {
  20490. // reduce banding
  20491. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  20492. }
  20493. Loop( steps, () => {
  20494. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  20495. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  20496. if ( material.depthNode !== null ) {
  20497. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  20498. builder.context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  20499. }
  20500. builder.context.positionWorld = positionRay;
  20501. builder.context.shadowPositionWorld = positionRay;
  20502. builder.context.positionView = positionViewRay;
  20503. scatteringDensity.assign( 0 );
  20504. let scatteringNode;
  20505. if ( material.scatteringNode ) {
  20506. scatteringNode = material.scatteringNode( {
  20507. positionRay
  20508. } );
  20509. }
  20510. super.start( builder );
  20511. if ( scatteringNode ) {
  20512. scatteringDensity.mulAssign( scatteringNode );
  20513. }
  20514. // beer's law
  20515. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  20516. transmittance.mulAssign( falloff );
  20517. // move along the ray
  20518. distTravelled.addAssign( stepSize );
  20519. } );
  20520. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  20521. }
  20522. scatteringLight( lightColor, builder ) {
  20523. const sceneDepthNode = builder.context.sceneDepthNode;
  20524. if ( sceneDepthNode ) {
  20525. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  20526. scatteringDensity.addAssign( lightColor );
  20527. } );
  20528. } else {
  20529. scatteringDensity.addAssign( lightColor );
  20530. }
  20531. }
  20532. direct( { lightNode, lightColor }, builder ) {
  20533. // Ignore lights with infinite distance
  20534. if ( lightNode.light.distance === undefined ) return;
  20535. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  20536. const directLight = lightColor.xyz.toVar();
  20537. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  20538. this.scatteringLight( directLight, builder );
  20539. }
  20540. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  20541. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  20542. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  20543. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  20544. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  20545. const P = builder.context.positionView;
  20546. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  20547. this.scatteringLight( directLight, builder );
  20548. }
  20549. finish( builder ) {
  20550. builder.context.outgoingLight.assign( outgoingRayLight );
  20551. }
  20552. }
  20553. /**
  20554. * Volume node material.
  20555. *
  20556. * @augments NodeMaterial
  20557. */
  20558. class VolumeNodeMaterial extends NodeMaterial {
  20559. static get type() {
  20560. return 'VolumeNodeMaterial';
  20561. }
  20562. /**
  20563. * Constructs a new volume node material.
  20564. *
  20565. * @param {Object} [parameters] - The configuration parameter.
  20566. */
  20567. constructor( parameters ) {
  20568. super();
  20569. /**
  20570. * This flag can be used for type testing.
  20571. *
  20572. * @type {boolean}
  20573. * @readonly
  20574. * @default true
  20575. */
  20576. this.isVolumeNodeMaterial = true;
  20577. /**
  20578. * Number of steps used for raymarching.
  20579. *
  20580. * @type {number}
  20581. * @default 25
  20582. */
  20583. this.steps = 25;
  20584. /**
  20585. * Offsets the distance a ray has been traveled through a volume.
  20586. * Can be used to implement dithering to reduce banding.
  20587. *
  20588. * @type {Node<float>}
  20589. * @default null
  20590. */
  20591. this.offsetNode = null;
  20592. /**
  20593. * Node used for scattering calculations.
  20594. *
  20595. * @type {Function|FunctionNode<vec4>}
  20596. * @default null
  20597. */
  20598. this.scatteringNode = null;
  20599. this.lights = true;
  20600. this.transparent = true;
  20601. this.side = BackSide;
  20602. this.depthTest = false;
  20603. this.depthWrite = false;
  20604. this.setValues( parameters );
  20605. }
  20606. setupLightingModel() {
  20607. return new VolumetricLightingModel();
  20608. }
  20609. }
  20610. /**
  20611. * This module manages the internal animation loop of the renderer.
  20612. *
  20613. * @private
  20614. */
  20615. class Animation {
  20616. /**
  20617. * Constructs a new animation loop management component.
  20618. *
  20619. * @param {Renderer} renderer - A reference to the main renderer.
  20620. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  20621. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20622. */
  20623. constructor( renderer, nodes, info ) {
  20624. /**
  20625. * A reference to the main renderer.
  20626. *
  20627. * @type {Renderer}
  20628. */
  20629. this.renderer = renderer;
  20630. /**
  20631. * Renderer component for managing nodes related logic.
  20632. *
  20633. * @type {NodeManager}
  20634. */
  20635. this.nodes = nodes;
  20636. /**
  20637. * Renderer component for managing metrics and monitoring data.
  20638. *
  20639. * @type {Info}
  20640. */
  20641. this.info = info;
  20642. /**
  20643. * A reference to the context from `requestAnimationFrame()` can
  20644. * be called (usually `window`).
  20645. *
  20646. * @type {?(Window|XRSession)}
  20647. */
  20648. this._context = typeof self !== 'undefined' ? self : null;
  20649. /**
  20650. * The user-defined animation loop.
  20651. *
  20652. * @type {?Function}
  20653. * @default null
  20654. */
  20655. this._animationLoop = null;
  20656. /**
  20657. * The requestId which is returned from the `requestAnimationFrame()` call.
  20658. * Can be used to cancel the stop the animation loop.
  20659. *
  20660. * @type {?number}
  20661. * @default null
  20662. */
  20663. this._requestId = null;
  20664. }
  20665. /**
  20666. * Starts the internal animation loop.
  20667. */
  20668. start() {
  20669. const update = ( time, xrFrame ) => {
  20670. this._requestId = this._context.requestAnimationFrame( update );
  20671. if ( this.info.autoReset === true ) this.info.reset();
  20672. this.nodes.nodeFrame.update();
  20673. this.info.frame = this.nodes.nodeFrame.frameId;
  20674. this.renderer._inspector.begin();
  20675. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  20676. this.renderer._inspector.finish();
  20677. };
  20678. update();
  20679. }
  20680. /**
  20681. * Stops the internal animation loop.
  20682. */
  20683. stop() {
  20684. if ( this._context !== null ) this._context.cancelAnimationFrame( this._requestId );
  20685. this._requestId = null;
  20686. }
  20687. /**
  20688. * Returns the user-level animation loop.
  20689. *
  20690. * @return {?Function} The animation loop.
  20691. */
  20692. getAnimationLoop() {
  20693. return this._animationLoop;
  20694. }
  20695. /**
  20696. * Defines the user-level animation loop.
  20697. *
  20698. * @param {?Function} callback - The animation loop.
  20699. */
  20700. setAnimationLoop( callback ) {
  20701. this._animationLoop = callback;
  20702. }
  20703. /**
  20704. * Returns the animation context.
  20705. *
  20706. * @return {Window|XRSession} The animation context.
  20707. */
  20708. getContext() {
  20709. return this._context;
  20710. }
  20711. /**
  20712. * Defines the context in which `requestAnimationFrame()` is executed.
  20713. *
  20714. * @param {Window|XRSession} context - The context to set.
  20715. */
  20716. setContext( context ) {
  20717. this._context = context;
  20718. }
  20719. /**
  20720. * Frees all internal resources and stops the animation loop.
  20721. */
  20722. dispose() {
  20723. this.stop();
  20724. }
  20725. }
  20726. /**
  20727. * Data structure for the renderer. It allows defining values
  20728. * with chained, hierarchical keys. Keys are meant to be
  20729. * objects since the module internally works with Weak Maps
  20730. * for performance reasons.
  20731. *
  20732. * @private
  20733. */
  20734. class ChainMap {
  20735. /**
  20736. * Constructs a new Chain Map.
  20737. */
  20738. constructor() {
  20739. /**
  20740. * A map of Weak Maps by their key length.
  20741. *
  20742. * @type {Object<number, WeakMap>}
  20743. */
  20744. this.weakMaps = {};
  20745. }
  20746. /**
  20747. * Returns the Weak Map for the given keys.
  20748. *
  20749. * @param {Array<Object>} keys - List of keys.
  20750. * @return {WeakMap} The weak map.
  20751. */
  20752. _getWeakMap( keys ) {
  20753. const length = keys.length;
  20754. let weakMap = this.weakMaps[ length ];
  20755. if ( weakMap === undefined ) {
  20756. weakMap = new WeakMap();
  20757. this.weakMaps[ length ] = weakMap;
  20758. }
  20759. return weakMap;
  20760. }
  20761. /**
  20762. * Returns the value for the given array of keys.
  20763. *
  20764. * @param {Array<Object>} keys - List of keys.
  20765. * @return {any} The value. Returns `undefined` if no value was found.
  20766. */
  20767. get( keys ) {
  20768. let map = this._getWeakMap( keys );
  20769. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20770. map = map.get( keys[ i ] );
  20771. if ( map === undefined ) return undefined;
  20772. }
  20773. return map.get( keys[ keys.length - 1 ] );
  20774. }
  20775. /**
  20776. * Sets the value for the given keys.
  20777. *
  20778. * @param {Array<Object>} keys - List of keys.
  20779. * @param {any} value - The value to set.
  20780. * @return {ChainMap} A reference to this Chain Map.
  20781. */
  20782. set( keys, value ) {
  20783. let map = this._getWeakMap( keys );
  20784. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20785. const key = keys[ i ];
  20786. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  20787. map = map.get( key );
  20788. }
  20789. map.set( keys[ keys.length - 1 ], value );
  20790. return this;
  20791. }
  20792. /**
  20793. * Deletes a value for the given keys.
  20794. *
  20795. * @param {Array<Object>} keys - The keys.
  20796. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  20797. */
  20798. delete( keys ) {
  20799. let map = this._getWeakMap( keys );
  20800. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20801. map = map.get( keys[ i ] );
  20802. if ( map === undefined ) return false;
  20803. }
  20804. return map.delete( keys[ keys.length - 1 ] );
  20805. }
  20806. }
  20807. let _id$a = 0;
  20808. const _protoKeysCache = new WeakMap();
  20809. function getKeys( obj ) {
  20810. const keys = Object.keys( obj );
  20811. let protoKeys = _protoKeysCache.get( obj.constructor );
  20812. if ( protoKeys === undefined ) {
  20813. protoKeys = [];
  20814. let proto = Object.getPrototypeOf( obj );
  20815. while ( proto ) {
  20816. const descriptors = Object.getOwnPropertyDescriptors( proto );
  20817. for ( const key in descriptors ) {
  20818. const descriptor = descriptors[ key ];
  20819. if ( descriptor && typeof descriptor.get === 'function' ) {
  20820. protoKeys.push( key );
  20821. }
  20822. }
  20823. proto = Object.getPrototypeOf( proto );
  20824. }
  20825. _protoKeysCache.set( obj.constructor, protoKeys );
  20826. }
  20827. for ( let i = 0; i < protoKeys.length; i ++ ) keys.push( protoKeys[ i ] );
  20828. return keys;
  20829. }
  20830. /**
  20831. * A render object is the renderer's representation of single entity that gets drawn
  20832. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  20833. * scene since render objects also depend from the used material, the current render context
  20834. * and the current scene's lighting.
  20835. *
  20836. * In general, the basic process of the renderer is:
  20837. *
  20838. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  20839. * - Process the render lists by calling one or more render commands for each render item.
  20840. * - For each render command, request a render object and perform the draw.
  20841. *
  20842. * The module provides an interface to get data required for the draw command like the actual
  20843. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  20844. * creating render objects should only be done when necessary.
  20845. *
  20846. * @private
  20847. */
  20848. class RenderObject {
  20849. /**
  20850. * Constructs a new render object.
  20851. *
  20852. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  20853. * @param {Geometries} geometries - Renderer component for managing geometries.
  20854. * @param {Renderer} renderer - The renderer.
  20855. * @param {Object3D} object - The 3D object.
  20856. * @param {Material} material - The 3D object's material.
  20857. * @param {Scene} scene - The scene the 3D object belongs to.
  20858. * @param {Camera} camera - The camera the object should be rendered with.
  20859. * @param {LightsNode} lightsNode - The lights node.
  20860. * @param {RenderContext} renderContext - The render context.
  20861. * @param {ClippingContext} clippingContext - The clipping context.
  20862. */
  20863. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  20864. this.id = _id$a ++;
  20865. /**
  20866. * Renderer component for managing nodes related logic.
  20867. *
  20868. * @type {NodeManager}
  20869. * @private
  20870. */
  20871. this._nodes = nodes;
  20872. /**
  20873. * Renderer component for managing geometries.
  20874. *
  20875. * @type {Geometries}
  20876. * @private
  20877. */
  20878. this._geometries = geometries;
  20879. /**
  20880. * The renderer.
  20881. *
  20882. * @type {Renderer}
  20883. */
  20884. this.renderer = renderer;
  20885. /**
  20886. * The 3D object.
  20887. *
  20888. * @type {Object3D}
  20889. */
  20890. this.object = object;
  20891. /**
  20892. * The 3D object's material.
  20893. *
  20894. * @type {Material}
  20895. */
  20896. this.material = material;
  20897. /**
  20898. * The scene the 3D object belongs to.
  20899. *
  20900. * @type {Scene}
  20901. */
  20902. this.scene = scene;
  20903. /**
  20904. * The camera the 3D object should be rendered with.
  20905. *
  20906. * @type {Camera}
  20907. */
  20908. this.camera = camera;
  20909. /**
  20910. * The lights node.
  20911. *
  20912. * @type {LightsNode}
  20913. */
  20914. this.lightsNode = lightsNode;
  20915. /**
  20916. * The render context.
  20917. *
  20918. * @type {RenderContext}
  20919. */
  20920. this.context = renderContext;
  20921. /**
  20922. * The 3D object's geometry.
  20923. *
  20924. * @type {BufferGeometry}
  20925. */
  20926. this.geometry = object.geometry;
  20927. /**
  20928. * The render object's version.
  20929. *
  20930. * @type {number}
  20931. */
  20932. this.version = material.version;
  20933. /**
  20934. * The draw range of the geometry.
  20935. *
  20936. * @type {?Object}
  20937. * @default null
  20938. */
  20939. this.drawRange = null;
  20940. /**
  20941. * An array holding the buffer attributes
  20942. * of the render object. This entails attribute
  20943. * definitions on geometry and node level.
  20944. *
  20945. * @type {?Array<BufferAttribute>}
  20946. * @default null
  20947. */
  20948. this.attributes = null;
  20949. /**
  20950. * An object holding the version of the
  20951. * attributes. The keys are the attribute names
  20952. * and the values are the attribute versions.
  20953. *
  20954. * @type {?Object<string, number>}
  20955. * @default null
  20956. */
  20957. this.attributesId = null;
  20958. /**
  20959. * A reference to a render pipeline the render
  20960. * object is processed with.
  20961. *
  20962. * @type {RenderPipeline}
  20963. * @default null
  20964. */
  20965. this.pipeline = null;
  20966. /**
  20967. * Only relevant for objects using
  20968. * multiple materials. This represents a group entry
  20969. * from the respective `BufferGeometry`.
  20970. *
  20971. * @type {?{start: number, count: number}}
  20972. * @default null
  20973. */
  20974. this.group = null;
  20975. /**
  20976. * An array holding the vertex buffers which can
  20977. * be buffer attributes but also interleaved buffers.
  20978. *
  20979. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  20980. * @default null
  20981. */
  20982. this.vertexBuffers = null;
  20983. /**
  20984. * The parameters for the draw command.
  20985. *
  20986. * @type {?Object}
  20987. * @default null
  20988. */
  20989. this.drawParams = null;
  20990. /**
  20991. * If this render object is used inside a render bundle,
  20992. * this property points to the respective bundle group.
  20993. *
  20994. * @type {?BundleGroup}
  20995. * @default null
  20996. */
  20997. this.bundle = null;
  20998. /**
  20999. * The clipping context.
  21000. *
  21001. * @type {ClippingContext}
  21002. */
  21003. this.clippingContext = clippingContext;
  21004. /**
  21005. * The clipping context's cache key.
  21006. *
  21007. * @type {string}
  21008. */
  21009. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  21010. /**
  21011. * The initial node cache key.
  21012. *
  21013. * @type {number}
  21014. */
  21015. this.initialNodesCacheKey = this.getDynamicCacheKey();
  21016. /**
  21017. * The initial cache key.
  21018. *
  21019. * @type {number}
  21020. */
  21021. this.initialCacheKey = this.getCacheKey();
  21022. /**
  21023. * The node builder state.
  21024. *
  21025. * @type {?NodeBuilderState}
  21026. * @private
  21027. * @default null
  21028. */
  21029. this._nodeBuilderState = null;
  21030. /**
  21031. * An array of bindings.
  21032. *
  21033. * @type {?Array<BindGroup>}
  21034. * @private
  21035. * @default null
  21036. */
  21037. this._bindings = null;
  21038. /**
  21039. * Reference to the node material observer.
  21040. *
  21041. * @type {?NodeMaterialObserver}
  21042. * @private
  21043. * @default null
  21044. */
  21045. this._monitor = null;
  21046. /**
  21047. * The object's original material when this render object is drawn with an
  21048. * override material.
  21049. *
  21050. * @type {?Material}
  21051. * @private
  21052. * @default null
  21053. */
  21054. this._sourceMaterial = renderer._currentSourceMaterial;
  21055. /**
  21056. * An event listener which is defined by `RenderObjects`. It performs
  21057. * clean up tasks when `dispose()` on this render object.
  21058. *
  21059. * @method
  21060. */
  21061. this.onDispose = null;
  21062. /**
  21063. * This flag can be used for type testing.
  21064. *
  21065. * @type {boolean}
  21066. * @readonly
  21067. * @default true
  21068. */
  21069. this.isRenderObject = true;
  21070. /**
  21071. * An event listener which is executed when `dispose()` is called on
  21072. * the material of this render object.
  21073. *
  21074. * @method
  21075. */
  21076. this.onMaterialDispose = () => {
  21077. this.dispose();
  21078. };
  21079. /**
  21080. * An event listener which is executed when `dispose()` is called on
  21081. * the geometry of this render object.
  21082. *
  21083. * @method
  21084. */
  21085. this.onGeometryDispose = () => {
  21086. // clear geometry cache attributes
  21087. this.attributes = null;
  21088. this.attributesId = null;
  21089. };
  21090. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  21091. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  21092. if ( this._sourceMaterial !== null ) {
  21093. this._sourceMaterial.addEventListener( 'dispose', this.onMaterialDispose );
  21094. }
  21095. }
  21096. /**
  21097. * Updates the clipping context.
  21098. *
  21099. * @param {ClippingContext} context - The clipping context to set.
  21100. */
  21101. updateClipping( context ) {
  21102. this.clippingContext = context;
  21103. }
  21104. /**
  21105. * Whether the clipping requires an update or not.
  21106. *
  21107. * @type {boolean}
  21108. * @readonly
  21109. */
  21110. get clippingNeedsUpdate() {
  21111. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  21112. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  21113. return true;
  21114. }
  21115. /**
  21116. * The number of clipping planes defined in context of hardware clipping.
  21117. *
  21118. * @type {number}
  21119. * @readonly
  21120. */
  21121. get hardwareClippingPlanes() {
  21122. return this.getNodeBuilderState().hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  21123. }
  21124. /**
  21125. * Returns the node builder state of this render object.
  21126. *
  21127. * @return {NodeBuilderState} The node builder state.
  21128. */
  21129. getNodeBuilderState() {
  21130. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  21131. }
  21132. /**
  21133. * Returns the node material observer of this render object.
  21134. *
  21135. * @return {NodeMaterialObserver} The node material observer.
  21136. */
  21137. getMonitor() {
  21138. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  21139. }
  21140. /**
  21141. * Returns an array of bind groups of this render object.
  21142. *
  21143. * @return {Array<BindGroup>} The bindings.
  21144. */
  21145. getBindings() {
  21146. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  21147. }
  21148. /**
  21149. * Returns a binding group by group name of this render object.
  21150. *
  21151. * @param {string} name - The name of the binding group.
  21152. * @return {?BindGroup} The bindings.
  21153. */
  21154. getBindingGroup( name ) {
  21155. for ( const bindingGroup of this.getBindings() ) {
  21156. if ( bindingGroup.name === name ) {
  21157. return bindingGroup;
  21158. }
  21159. }
  21160. }
  21161. /**
  21162. * Returns the index of the render object's geometry.
  21163. *
  21164. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  21165. */
  21166. getIndex() {
  21167. return this._geometries.getIndex( this );
  21168. }
  21169. /**
  21170. * Returns the indirect buffer attribute.
  21171. *
  21172. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  21173. */
  21174. getIndirect() {
  21175. return this._geometries.getIndirect( this );
  21176. }
  21177. /**
  21178. * Returns the byte offset into the indirect attribute buffer.
  21179. *
  21180. * @return {number|Array<number>} The byte offset into the indirect attribute buffer.
  21181. */
  21182. getIndirectOffset() {
  21183. return this._geometries.getIndirectOffset( this );
  21184. }
  21185. /**
  21186. * Returns an array that acts as a key for identifying the render object in a chain map.
  21187. *
  21188. * @return {Array<Object>} An array with object references.
  21189. */
  21190. getChainArray() {
  21191. return [ this.object, this.material, this.context, this.lightsNode ];
  21192. }
  21193. /**
  21194. * This method is used when the geometry of a 3D object has been exchanged and the
  21195. * respective render object now requires an update.
  21196. *
  21197. * @param {BufferGeometry} geometry - The geometry to set.
  21198. */
  21199. setGeometry( geometry ) {
  21200. this.geometry = geometry;
  21201. this.attributes = null;
  21202. this.attributesId = null;
  21203. }
  21204. /**
  21205. * Returns the buffer attributes of the render object. The returned array holds
  21206. * attribute definitions on geometry and node level.
  21207. *
  21208. * @return {Array<BufferAttribute>} An array with buffer attributes.
  21209. */
  21210. getAttributes() {
  21211. if ( this.attributes !== null ) return this.attributes;
  21212. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  21213. const geometry = this.geometry;
  21214. const attributes = [];
  21215. const vertexBuffers = new Set();
  21216. const attributesId = {};
  21217. for ( const nodeAttribute of nodeAttributes ) {
  21218. let attribute;
  21219. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  21220. // node attribute
  21221. attribute = nodeAttribute.node.attribute;
  21222. } else {
  21223. // geometry attribute
  21224. attribute = geometry.getAttribute( nodeAttribute.name );
  21225. if ( attribute !== undefined ) {
  21226. if ( attribute.isInterleavedBufferAttribute ) {
  21227. attributesId[ nodeAttribute.name ] = attribute.data.uuid;
  21228. } else {
  21229. attributesId[ nodeAttribute.name ] = attribute.id;
  21230. }
  21231. }
  21232. }
  21233. if ( attribute === undefined ) continue;
  21234. attributes.push( attribute );
  21235. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  21236. vertexBuffers.add( bufferAttribute );
  21237. }
  21238. this.attributes = attributes;
  21239. this.attributesId = attributesId;
  21240. this.vertexBuffers = Array.from( vertexBuffers.values() );
  21241. return attributes;
  21242. }
  21243. /**
  21244. * Returns the vertex buffers of the render object.
  21245. *
  21246. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  21247. */
  21248. getVertexBuffers() {
  21249. if ( this.vertexBuffers === null ) this.getAttributes();
  21250. return this.vertexBuffers;
  21251. }
  21252. /**
  21253. * Returns the draw parameters for the render object.
  21254. *
  21255. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  21256. */
  21257. getDrawParameters() {
  21258. const { object, material, geometry, group, drawRange } = this;
  21259. const drawParams = this.drawParams || ( this.drawParams = {
  21260. vertexCount: 0,
  21261. firstVertex: 0,
  21262. instanceCount: 0,
  21263. firstInstance: 0
  21264. } );
  21265. const index = this.getIndex();
  21266. const hasIndex = ( index !== null );
  21267. let instanceCount = 1;
  21268. if ( geometry.isInstancedBufferGeometry === true ) {
  21269. instanceCount = geometry.instanceCount;
  21270. } else if ( object.count !== undefined ) {
  21271. instanceCount = Math.max( 0, object.count );
  21272. }
  21273. if ( instanceCount === 0 ) return null;
  21274. drawParams.instanceCount = instanceCount;
  21275. if ( object.isBatchedMesh === true ) return drawParams;
  21276. let rangeFactor = 1;
  21277. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  21278. rangeFactor = 2;
  21279. }
  21280. let firstVertex = drawRange.start * rangeFactor;
  21281. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  21282. if ( group !== null ) {
  21283. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  21284. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  21285. }
  21286. const position = geometry.attributes.position;
  21287. let itemCount = Infinity;
  21288. if ( hasIndex ) {
  21289. itemCount = index.count;
  21290. } else if ( position !== undefined && position !== null ) {
  21291. itemCount = position.count;
  21292. }
  21293. firstVertex = Math.max( firstVertex, 0 );
  21294. lastVertex = Math.min( lastVertex, itemCount );
  21295. const count = lastVertex - firstVertex;
  21296. if ( count < 0 || count === Infinity ) return null;
  21297. drawParams.vertexCount = count;
  21298. drawParams.firstVertex = firstVertex;
  21299. return drawParams;
  21300. }
  21301. /**
  21302. * Returns the render object's geometry cache key.
  21303. *
  21304. * The geometry cache key is part of the material cache key.
  21305. *
  21306. * @return {string} The geometry cache key.
  21307. */
  21308. getGeometryCacheKey() {
  21309. const { geometry } = this;
  21310. let cacheKey = '';
  21311. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  21312. const attribute = geometry.attributes[ name ];
  21313. cacheKey += name + ',';
  21314. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  21315. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  21316. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  21317. if ( attribute.normalized ) cacheKey += 'n,';
  21318. }
  21319. // structural equality isn't sufficient for morph targets since the
  21320. // data are maintained in textures. only if the targets are all equal
  21321. // the texture and thus the `morphReference` can be shared.
  21322. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  21323. const targets = geometry.morphAttributes[ name ];
  21324. cacheKey += 'morph-' + name + ',';
  21325. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  21326. const attribute = targets[ i ];
  21327. cacheKey += attribute.id + ',';
  21328. }
  21329. }
  21330. if ( geometry.index ) {
  21331. cacheKey += 'index,';
  21332. }
  21333. return cacheKey;
  21334. }
  21335. /**
  21336. * Returns the render object's material cache key.
  21337. *
  21338. * The material cache key is part of the render object cache key.
  21339. *
  21340. * @return {number} The material cache key.
  21341. */
  21342. getMaterialCacheKey() {
  21343. const { object, material, renderer } = this;
  21344. let cacheKey = material.customProgramCacheKey();
  21345. for ( const property of getKeys( material ) ) {
  21346. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  21347. const value = material[ property ];
  21348. let valueKey;
  21349. if ( value !== null ) {
  21350. // some material values require a formatting
  21351. const type = typeof value;
  21352. if ( type === 'number' ) {
  21353. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  21354. } else if ( type === 'object' ) {
  21355. valueKey = '{';
  21356. if ( value.isTexture ) {
  21357. valueKey += value.mapping;
  21358. // WebGPU must honor the sampler data because they are part of the bindings
  21359. if ( renderer.backend.isWebGPUBackend === true ) {
  21360. valueKey += value.magFilter;
  21361. valueKey += value.minFilter;
  21362. valueKey += value.wrapS;
  21363. valueKey += value.wrapT;
  21364. valueKey += value.wrapR;
  21365. }
  21366. }
  21367. valueKey += '}';
  21368. } else {
  21369. valueKey = String( value );
  21370. }
  21371. } else {
  21372. valueKey = String( value );
  21373. }
  21374. cacheKey += /*property + ':' +*/ valueKey + ',';
  21375. }
  21376. cacheKey += this.clippingContextCacheKey + ',';
  21377. if ( object.geometry ) {
  21378. cacheKey += this.getGeometryCacheKey();
  21379. }
  21380. if ( object.skeleton ) {
  21381. cacheKey += object.skeleton.bones.length + ',';
  21382. }
  21383. if ( object.isBatchedMesh ) {
  21384. cacheKey += object._matricesTexture.uuid + ',';
  21385. if ( object._colorsTexture !== null ) {
  21386. cacheKey += object._colorsTexture.uuid + ',';
  21387. }
  21388. }
  21389. if ( object.isInstancedMesh || object.count > 1 ) {
  21390. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  21391. cacheKey += object.uuid + ',';
  21392. }
  21393. cacheKey += this.context.id + ',';
  21394. cacheKey += object.receiveShadow + ',';
  21395. return hashString( cacheKey );
  21396. }
  21397. /**
  21398. * Whether the geometry requires an update or not.
  21399. *
  21400. * @type {boolean}
  21401. * @readonly
  21402. */
  21403. get needsGeometryUpdate() {
  21404. if ( this.geometry.id !== this.object.geometry.id ) return true;
  21405. if ( this.attributes !== null ) {
  21406. const attributesId = this.attributesId;
  21407. for ( const name in attributesId ) {
  21408. const attribute = this.geometry.getAttribute( name );
  21409. if ( attribute === undefined ) return true;
  21410. const id = attribute.isInterleavedBufferAttribute ? attribute.data.uuid : attribute.id;
  21411. if ( attributesId[ name ] !== id ) {
  21412. return true;
  21413. }
  21414. }
  21415. }
  21416. return false;
  21417. }
  21418. /**
  21419. * Whether the render object requires an update or not.
  21420. *
  21421. * Note: There are two distinct places where render objects are checked for an update.
  21422. *
  21423. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  21424. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  21425. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  21426. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  21427. * a need for a refresh due to material, geometry or object related value changes.
  21428. *
  21429. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  21430. * that performs the 'needsUpdate' check.
  21431. *
  21432. * @type {boolean}
  21433. * @readonly
  21434. */
  21435. get needsUpdate() {
  21436. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  21437. }
  21438. /**
  21439. * Returns the dynamic cache key which represents a key that is computed per draw command.
  21440. *
  21441. * @return {number} The cache key.
  21442. */
  21443. getDynamicCacheKey() {
  21444. let cacheKey = 0;
  21445. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  21446. // the renderer is inside a shadow pass.
  21447. if ( this.material.isShadowPassMaterial !== true ) {
  21448. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  21449. }
  21450. if ( this.camera.isArrayCamera ) {
  21451. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  21452. }
  21453. if ( this.object.receiveShadow ) {
  21454. cacheKey = hash$1( cacheKey, 1 );
  21455. }
  21456. cacheKey = hash$1( cacheKey, this.renderer.contextNode.id, this.renderer.contextNode.version );
  21457. return cacheKey;
  21458. }
  21459. /**
  21460. * Returns the render object's cache key.
  21461. *
  21462. * @return {number} The cache key.
  21463. */
  21464. getCacheKey() {
  21465. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  21466. }
  21467. /**
  21468. * Frees internal resources.
  21469. */
  21470. dispose() {
  21471. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  21472. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  21473. if ( this._sourceMaterial !== null ) {
  21474. this._sourceMaterial.removeEventListener( 'dispose', this.onMaterialDispose );
  21475. }
  21476. this.onDispose();
  21477. }
  21478. }
  21479. const _chainKeys$3 = [];
  21480. /**
  21481. * This module manages the render objects of the renderer.
  21482. *
  21483. * @private
  21484. */
  21485. class RenderObjects {
  21486. /**
  21487. * Constructs a new render object management component.
  21488. *
  21489. * @param {Renderer} renderer - The renderer.
  21490. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  21491. * @param {Geometries} geometries - Renderer component for managing geometries.
  21492. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  21493. * @param {Bindings} bindings - Renderer component for managing bindings.
  21494. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21495. */
  21496. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  21497. /**
  21498. * The renderer.
  21499. *
  21500. * @type {Renderer}
  21501. */
  21502. this.renderer = renderer;
  21503. /**
  21504. * Renderer component for managing nodes related logic.
  21505. *
  21506. * @type {NodeManager}
  21507. */
  21508. this.nodes = nodes;
  21509. /**
  21510. * Renderer component for managing geometries.
  21511. *
  21512. * @type {Geometries}
  21513. */
  21514. this.geometries = geometries;
  21515. /**
  21516. * Renderer component for managing pipelines.
  21517. *
  21518. * @type {Pipelines}
  21519. */
  21520. this.pipelines = pipelines;
  21521. /**
  21522. * Renderer component for managing bindings.
  21523. *
  21524. * @type {Bindings}
  21525. */
  21526. this.bindings = bindings;
  21527. /**
  21528. * Renderer component for managing metrics and monitoring data.
  21529. *
  21530. * @type {Info}
  21531. */
  21532. this.info = info;
  21533. /**
  21534. * A dictionary that manages render contexts in chain maps
  21535. * for each pass ID.
  21536. *
  21537. * @type {Object<string,ChainMap>}
  21538. */
  21539. this.chainMaps = {};
  21540. }
  21541. /**
  21542. * Returns a render object for the given object and state data.
  21543. *
  21544. * @param {Object3D} object - The 3D object.
  21545. * @param {Material} material - The 3D object's material.
  21546. * @param {Scene} scene - The scene the 3D object belongs to.
  21547. * @param {Camera} camera - The camera the 3D object should be rendered with.
  21548. * @param {LightsNode} lightsNode - The lights node.
  21549. * @param {RenderContext} renderContext - The render context.
  21550. * @param {ClippingContext} clippingContext - The clipping context.
  21551. * @param {string} [passId] - An optional ID for identifying the pass.
  21552. * @return {RenderObject} The render object.
  21553. */
  21554. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  21555. const chainMap = this.getChainMap( passId );
  21556. // set chain keys
  21557. _chainKeys$3[ 0 ] = object;
  21558. _chainKeys$3[ 1 ] = material;
  21559. _chainKeys$3[ 2 ] = renderContext;
  21560. _chainKeys$3[ 3 ] = lightsNode;
  21561. //
  21562. let renderObject = chainMap.get( _chainKeys$3 );
  21563. if ( renderObject === undefined ) {
  21564. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  21565. chainMap.set( _chainKeys$3, renderObject );
  21566. } else {
  21567. // update references
  21568. renderObject.camera = camera;
  21569. //
  21570. renderObject.updateClipping( clippingContext );
  21571. if ( renderObject.needsGeometryUpdate ) {
  21572. renderObject.setGeometry( object.geometry );
  21573. }
  21574. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  21575. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  21576. renderObject.dispose();
  21577. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  21578. } else {
  21579. renderObject.version = material.version;
  21580. }
  21581. }
  21582. }
  21583. // reset chain array
  21584. _chainKeys$3[ 0 ] = null;
  21585. _chainKeys$3[ 1 ] = null;
  21586. _chainKeys$3[ 2 ] = null;
  21587. _chainKeys$3[ 3 ] = null;
  21588. //
  21589. return renderObject;
  21590. }
  21591. /**
  21592. * Returns a chain map for the given pass ID.
  21593. *
  21594. * @param {string} [passId='default'] - The pass ID.
  21595. * @return {ChainMap} The chain map.
  21596. */
  21597. getChainMap( passId = 'default' ) {
  21598. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  21599. }
  21600. /**
  21601. * Frees internal resources.
  21602. */
  21603. dispose() {
  21604. this.chainMaps = {};
  21605. }
  21606. /**
  21607. * Factory method for creating render objects with the given list of parameters.
  21608. *
  21609. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  21610. * @param {Geometries} geometries - Renderer component for managing geometries.
  21611. * @param {Renderer} renderer - The renderer.
  21612. * @param {Object3D} object - The 3D object.
  21613. * @param {Material} material - The object's material.
  21614. * @param {Scene} scene - The scene the 3D object belongs to.
  21615. * @param {Camera} camera - The camera the object should be rendered with.
  21616. * @param {LightsNode} lightsNode - The lights node.
  21617. * @param {RenderContext} renderContext - The render context.
  21618. * @param {ClippingContext} clippingContext - The clipping context.
  21619. * @param {string} [passId] - An optional ID for identifying the pass.
  21620. * @return {RenderObject} The render object.
  21621. */
  21622. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  21623. const chainMap = this.getChainMap( passId );
  21624. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  21625. renderObject.onDispose = () => {
  21626. this.pipelines.delete( renderObject );
  21627. this.bindings.deleteForRender( renderObject );
  21628. this.nodes.delete( renderObject );
  21629. chainMap.delete( renderObject.getChainArray() );
  21630. };
  21631. return renderObject;
  21632. }
  21633. }
  21634. /**
  21635. * Data structure for the renderer. It is intended to manage
  21636. * data of objects in dictionaries.
  21637. *
  21638. * @private
  21639. */
  21640. class DataMap {
  21641. /**
  21642. * Constructs a new data map.
  21643. */
  21644. constructor() {
  21645. /**
  21646. * `DataMap` internally uses a weak map
  21647. * to manage its data.
  21648. *
  21649. * @type {WeakMap<Object, Object>}
  21650. */
  21651. this.data = new WeakMap();
  21652. }
  21653. /**
  21654. * Returns the dictionary for the given object.
  21655. *
  21656. * @param {Object} object - The object.
  21657. * @return {Object} The dictionary.
  21658. */
  21659. get( object ) {
  21660. let map = this.data.get( object );
  21661. if ( map === undefined ) {
  21662. map = {};
  21663. this.data.set( object, map );
  21664. }
  21665. return map;
  21666. }
  21667. /**
  21668. * Deletes the dictionary for the given object.
  21669. *
  21670. * @param {Object} object - The object.
  21671. * @return {?Object} The deleted dictionary.
  21672. */
  21673. delete( object ) {
  21674. let map = null;
  21675. if ( this.data.has( object ) ) {
  21676. map = this.data.get( object );
  21677. this.data.delete( object );
  21678. }
  21679. return map;
  21680. }
  21681. /**
  21682. * Returns `true` if the given object has a dictionary defined.
  21683. *
  21684. * @param {Object} object - The object to test.
  21685. * @return {boolean} Whether a dictionary is defined or not.
  21686. */
  21687. has( object ) {
  21688. return this.data.has( object );
  21689. }
  21690. /**
  21691. * Frees internal resources.
  21692. */
  21693. dispose() {
  21694. this.data = new WeakMap();
  21695. }
  21696. }
  21697. const AttributeType = {
  21698. VERTEX: 1,
  21699. INDEX: 2,
  21700. STORAGE: 3,
  21701. INDIRECT: 4
  21702. };
  21703. // size of a chunk in bytes (STD140 layout)
  21704. const GPU_CHUNK_BYTES = 16;
  21705. // @TODO: Move to src/constants.js
  21706. const BlendColorFactor = 211;
  21707. const OneMinusBlendColorFactor = 212;
  21708. /**
  21709. * This renderer module manages geometry attributes.
  21710. *
  21711. * @private
  21712. * @augments DataMap
  21713. */
  21714. class Attributes extends DataMap {
  21715. /**
  21716. * Constructs a new attribute management component.
  21717. *
  21718. * @param {Backend} backend - The renderer's backend.
  21719. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21720. */
  21721. constructor( backend, info ) {
  21722. super();
  21723. /**
  21724. * The renderer's backend.
  21725. *
  21726. * @type {Backend}
  21727. */
  21728. this.backend = backend;
  21729. /**
  21730. * Renderer component for managing metrics and monitoring data.
  21731. *
  21732. * @type {Info}
  21733. */
  21734. this.info = info;
  21735. }
  21736. /**
  21737. * Deletes the data for the given attribute.
  21738. *
  21739. * @param {BufferAttribute} attribute - The attribute.
  21740. * @return {?Object} The deleted attribute data.
  21741. */
  21742. delete( attribute ) {
  21743. const attributeData = super.delete( attribute );
  21744. if ( attributeData !== null ) {
  21745. this.backend.destroyAttribute( attribute );
  21746. this.info.destroyAttribute( attribute );
  21747. }
  21748. return attributeData;
  21749. }
  21750. /**
  21751. * Updates the given attribute. This method creates attribute buffers
  21752. * for new attributes and updates data for existing ones.
  21753. *
  21754. * @param {BufferAttribute} attribute - The attribute to update.
  21755. * @param {number} type - The attribute type.
  21756. */
  21757. update( attribute, type ) {
  21758. const data = this.get( attribute );
  21759. if ( data.version === undefined ) {
  21760. if ( type === AttributeType.VERTEX ) {
  21761. this.backend.createAttribute( attribute );
  21762. this.info.createAttribute( attribute );
  21763. } else if ( type === AttributeType.INDEX ) {
  21764. this.backend.createIndexAttribute( attribute );
  21765. this.info.createIndexAttribute( attribute );
  21766. } else if ( type === AttributeType.STORAGE ) {
  21767. this.backend.createStorageAttribute( attribute );
  21768. this.info.createStorageAttribute( attribute );
  21769. } else if ( type === AttributeType.INDIRECT ) {
  21770. this.backend.createIndirectStorageAttribute( attribute );
  21771. this.info.createIndirectStorageAttribute( attribute );
  21772. }
  21773. data.version = this._getBufferAttribute( attribute ).version;
  21774. } else {
  21775. const bufferAttribute = this._getBufferAttribute( attribute );
  21776. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  21777. this.backend.updateAttribute( attribute );
  21778. data.version = bufferAttribute.version;
  21779. }
  21780. }
  21781. }
  21782. /**
  21783. * Utility method for handling interleaved buffer attributes correctly.
  21784. * To process them, their `InterleavedBuffer` is returned.
  21785. *
  21786. * @param {BufferAttribute} attribute - The attribute.
  21787. * @return {BufferAttribute|InterleavedBuffer}
  21788. */
  21789. _getBufferAttribute( attribute ) {
  21790. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21791. return attribute;
  21792. }
  21793. }
  21794. /**
  21795. * Returns the wireframe version for the given geometry.
  21796. *
  21797. * @private
  21798. * @function
  21799. * @param {BufferGeometry} geometry - The geometry.
  21800. * @return {number} The version.
  21801. */
  21802. function getWireframeVersion( geometry ) {
  21803. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  21804. }
  21805. /**
  21806. * Returns the wireframe ID for the given geometry.
  21807. *
  21808. * @private
  21809. * @function
  21810. * @param {BufferGeometry} geometry - The geometry.
  21811. * @return {number} The ID.
  21812. */
  21813. function getWireframeId( geometry ) {
  21814. return ( geometry.index !== null ) ? geometry.index.id : geometry.attributes.position.id;
  21815. }
  21816. /**
  21817. * Returns a wireframe index attribute for the given geometry.
  21818. *
  21819. * @private
  21820. * @function
  21821. * @param {BufferGeometry} geometry - The geometry.
  21822. * @return {BufferAttribute} The wireframe index attribute.
  21823. */
  21824. function getWireframeIndex( geometry ) {
  21825. const indices = [];
  21826. const geometryIndex = geometry.index;
  21827. const geometryPosition = geometry.attributes.position;
  21828. if ( geometryIndex !== null ) {
  21829. const array = geometryIndex.array;
  21830. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  21831. const a = array[ i + 0 ];
  21832. const b = array[ i + 1 ];
  21833. const c = array[ i + 2 ];
  21834. indices.push( a, b, b, c, c, a );
  21835. }
  21836. } else {
  21837. const array = geometryPosition.array;
  21838. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  21839. const a = i + 0;
  21840. const b = i + 1;
  21841. const c = i + 2;
  21842. indices.push( a, b, b, c, c, a );
  21843. }
  21844. }
  21845. const attribute = new ( geometryPosition.count >= 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  21846. attribute.version = getWireframeVersion( geometry );
  21847. attribute.__id = getWireframeId( geometry );
  21848. return attribute;
  21849. }
  21850. /**
  21851. * This renderer module manages geometries.
  21852. *
  21853. * @private
  21854. * @augments DataMap
  21855. */
  21856. class Geometries extends DataMap {
  21857. /**
  21858. * Constructs a new geometry management component.
  21859. *
  21860. * @param {Attributes} attributes - Renderer component for managing attributes.
  21861. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21862. */
  21863. constructor( attributes, info ) {
  21864. super();
  21865. /**
  21866. * Renderer component for managing attributes.
  21867. *
  21868. * @type {Attributes}
  21869. */
  21870. this.attributes = attributes;
  21871. /**
  21872. * Renderer component for managing metrics and monitoring data.
  21873. *
  21874. * @type {Info}
  21875. */
  21876. this.info = info;
  21877. /**
  21878. * Weak Map for managing attributes for wireframe rendering.
  21879. *
  21880. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  21881. */
  21882. this.wireframes = new WeakMap();
  21883. /**
  21884. * This Weak Map is used to make sure buffer attributes are
  21885. * updated only once per render call.
  21886. *
  21887. * @type {WeakMap<BufferAttribute,number>}
  21888. */
  21889. this.attributeCall = new WeakMap();
  21890. /**
  21891. * Stores the event listeners attached to geometries.
  21892. *
  21893. * @private
  21894. * @type {Map<BufferGeometry,Function>}
  21895. */
  21896. this._geometryDisposeListeners = new Map();
  21897. }
  21898. /**
  21899. * Returns `true` if the given render object has an initialized geometry.
  21900. *
  21901. * @param {RenderObject} renderObject - The render object.
  21902. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  21903. */
  21904. has( renderObject ) {
  21905. const geometry = renderObject.geometry;
  21906. return super.has( geometry ) && this.get( geometry ).initialized === true;
  21907. }
  21908. /**
  21909. * Prepares the geometry of the given render object for rendering.
  21910. *
  21911. * @param {RenderObject} renderObject - The render object.
  21912. */
  21913. updateForRender( renderObject ) {
  21914. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  21915. this.updateAttributes( renderObject );
  21916. }
  21917. /**
  21918. * Initializes the geometry of the given render object.
  21919. *
  21920. * @param {RenderObject} renderObject - The render object.
  21921. */
  21922. initGeometry( renderObject ) {
  21923. const geometry = renderObject.geometry;
  21924. const geometryData = this.get( geometry );
  21925. geometryData.initialized = true;
  21926. this.info.memory.geometries ++;
  21927. const onDispose = () => {
  21928. this.info.memory.geometries --;
  21929. const index = geometry.index;
  21930. const geometryAttributes = renderObject.getAttributes();
  21931. if ( index !== null ) {
  21932. this.attributes.delete( index );
  21933. }
  21934. for ( const geometryAttribute of geometryAttributes ) {
  21935. this.attributes.delete( geometryAttribute );
  21936. }
  21937. const wireframeAttribute = this.wireframes.get( geometry );
  21938. if ( wireframeAttribute !== undefined ) {
  21939. this.attributes.delete( wireframeAttribute );
  21940. }
  21941. geometry.removeEventListener( 'dispose', onDispose );
  21942. this._geometryDisposeListeners.delete( geometry );
  21943. };
  21944. geometry.addEventListener( 'dispose', onDispose );
  21945. // see #31798 why tracking separate remove listeners is required right now
  21946. // TODO: Re-evaluate how onDispose() is managed in this component
  21947. this._geometryDisposeListeners.set( geometry, onDispose );
  21948. }
  21949. /**
  21950. * Updates the geometry attributes of the given render object.
  21951. *
  21952. * @param {RenderObject} renderObject - The render object.
  21953. */
  21954. updateAttributes( renderObject ) {
  21955. // attributes
  21956. const attributes = renderObject.getAttributes();
  21957. for ( const attribute of attributes ) {
  21958. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  21959. this.updateAttribute( attribute, AttributeType.STORAGE );
  21960. } else {
  21961. this.updateAttribute( attribute, AttributeType.VERTEX );
  21962. }
  21963. }
  21964. // indexes
  21965. const index = this.getIndex( renderObject );
  21966. if ( index !== null ) {
  21967. this.updateAttribute( index, AttributeType.INDEX );
  21968. }
  21969. // indirect
  21970. const indirect = renderObject.geometry.indirect;
  21971. if ( indirect !== null ) {
  21972. this.updateAttribute( indirect, AttributeType.INDIRECT );
  21973. }
  21974. }
  21975. /**
  21976. * Updates the given attribute.
  21977. *
  21978. * @param {BufferAttribute} attribute - The attribute to update.
  21979. * @param {number} type - The attribute type.
  21980. */
  21981. updateAttribute( attribute, type ) {
  21982. const callId = this.info.render.calls;
  21983. if ( ! attribute.isInterleavedBufferAttribute ) {
  21984. if ( this.attributeCall.get( attribute ) !== callId ) {
  21985. this.attributes.update( attribute, type );
  21986. this.attributeCall.set( attribute, callId );
  21987. }
  21988. } else {
  21989. if ( this.attributeCall.get( attribute ) === undefined ) {
  21990. this.attributes.update( attribute, type );
  21991. this.attributeCall.set( attribute, callId );
  21992. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  21993. this.attributes.update( attribute, type );
  21994. this.attributeCall.set( attribute.data, callId );
  21995. this.attributeCall.set( attribute, callId );
  21996. }
  21997. }
  21998. }
  21999. /**
  22000. * Returns the indirect buffer attribute of the given render object.
  22001. *
  22002. * @param {RenderObject} renderObject - The render object.
  22003. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  22004. */
  22005. getIndirect( renderObject ) {
  22006. return renderObject.geometry.indirect;
  22007. }
  22008. /**
  22009. * Returns the byte offset into the indirect attribute buffer of the given render object.
  22010. *
  22011. * @param {RenderObject} renderObject - The render object.
  22012. * @return {number} The byte offset into the indirect attribute buffer.
  22013. */
  22014. getIndirectOffset( renderObject ) {
  22015. return renderObject.geometry.indirectOffset;
  22016. }
  22017. /**
  22018. * Returns the index of the given render object's geometry. This is implemented
  22019. * in a method to return a wireframe index if necessary.
  22020. *
  22021. * @param {RenderObject} renderObject - The render object.
  22022. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  22023. */
  22024. getIndex( renderObject ) {
  22025. const { geometry, material } = renderObject;
  22026. let index = geometry.index;
  22027. if ( material.wireframe === true ) {
  22028. const wireframes = this.wireframes;
  22029. let wireframeAttribute = wireframes.get( geometry );
  22030. if ( wireframeAttribute === undefined ) {
  22031. wireframeAttribute = getWireframeIndex( geometry );
  22032. wireframes.set( geometry, wireframeAttribute );
  22033. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) || wireframeAttribute.__id !== getWireframeId( geometry ) ) {
  22034. this.attributes.delete( wireframeAttribute );
  22035. wireframeAttribute = getWireframeIndex( geometry );
  22036. wireframes.set( geometry, wireframeAttribute );
  22037. }
  22038. index = wireframeAttribute;
  22039. }
  22040. return index;
  22041. }
  22042. dispose() {
  22043. for ( const [ geometry, onDispose ] of this._geometryDisposeListeners.entries() ) {
  22044. geometry.removeEventListener( 'dispose', onDispose );
  22045. }
  22046. this._geometryDisposeListeners.clear();
  22047. }
  22048. }
  22049. /**
  22050. * This renderer module provides a series of statistical information
  22051. * about the GPU memory and the rendering process. Useful for debugging
  22052. * and monitoring.
  22053. */
  22054. class Info {
  22055. /**
  22056. * Constructs a new info component.
  22057. */
  22058. constructor() {
  22059. /**
  22060. * Whether frame related metrics should automatically
  22061. * be resetted or not. This property should be set to `false`
  22062. * by apps which manage their own animation loop. They must
  22063. * then call `renderer.info.reset()` once per frame manually.
  22064. *
  22065. * @type {boolean}
  22066. * @default true
  22067. */
  22068. this.autoReset = true;
  22069. /**
  22070. * The current frame ID. This ID is managed
  22071. * by `NodeFrame`.
  22072. *
  22073. * @type {number}
  22074. * @readonly
  22075. * @default 0
  22076. */
  22077. this.frame = 0;
  22078. /**
  22079. * The number of render calls since the
  22080. * app has been started.
  22081. *
  22082. * @type {number}
  22083. * @readonly
  22084. * @default 0
  22085. */
  22086. this.calls = 0;
  22087. /**
  22088. * Render related metrics.
  22089. *
  22090. * @type {Object}
  22091. * @readonly
  22092. * @property {number} calls - The number of render calls since the app has been started.
  22093. * @property {number} frameCalls - The number of render calls of the current frame.
  22094. * @property {number} drawCalls - The number of draw calls of the current frame.
  22095. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  22096. * @property {number} points - The number of rendered point primitives of the current frame.
  22097. * @property {number} lines - The number of rendered line primitives of the current frame.
  22098. * @property {number} timestamp - The timestamp of the frame.
  22099. */
  22100. this.render = {
  22101. calls: 0,
  22102. frameCalls: 0,
  22103. drawCalls: 0,
  22104. triangles: 0,
  22105. points: 0,
  22106. lines: 0,
  22107. timestamp: 0,
  22108. };
  22109. /**
  22110. * Compute related metrics.
  22111. *
  22112. * @type {Object}
  22113. * @readonly
  22114. * @property {number} calls - The number of compute calls since the app has been started.
  22115. * @property {number} frameCalls - The number of compute calls of the current frame.
  22116. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  22117. */
  22118. this.compute = {
  22119. calls: 0,
  22120. frameCalls: 0,
  22121. timestamp: 0
  22122. };
  22123. /**
  22124. * Memory related metrics.
  22125. *
  22126. * @type {Object}
  22127. * @readonly
  22128. * @property {number} attributes - The number of active attributes.
  22129. * @property {number} attributesSize - The memory size of active attributes in bytes.
  22130. * @property {number} geometries - The number of active geometries.
  22131. * @property {number} indexAttributes - The number of active index attributes.
  22132. * @property {number} indexAttributesSize - The memory size of active index attributes in bytes.
  22133. * @property {number} indirectStorageAttributes - The number of active indirect storage attributes.
  22134. * @property {number} indirectStorageAttributesSize - The memory size of active indirect storage attributes in bytes.
  22135. * @property {number} programs - The number of active programs.
  22136. * @property {number} programsSize - The memory size of active programs in bytes.
  22137. * @property {number} readbackBuffers - The number of active readback buffers.
  22138. * @property {number} readbackBuffersSize - The memory size of active readback buffers in bytes.
  22139. * @property {number} renderTargets - The number of active renderTargets.
  22140. * @property {number} storageAttributes - The number of active storage attributes.
  22141. * @property {number} storageAttributesSize - The memory size of active storage attributes in bytes.
  22142. * @property {number} textures - The number of active textures.
  22143. * @property {number} texturesSize - The memory size of active textures in bytes.
  22144. * @property {number} uniformBuffers - The number of active uniform buffers.
  22145. * @property {number} uniformBuffersSize - The memory size of active uniform buffers in bytes.
  22146. * @property {number} total - The total memory size in bytes.
  22147. */
  22148. this.memory = {
  22149. attributes: 0,
  22150. attributesSize: 0,
  22151. geometries: 0,
  22152. indexAttributes: 0,
  22153. indexAttributesSize: 0,
  22154. indirectStorageAttributes: 0,
  22155. indirectStorageAttributesSize: 0,
  22156. programs: 0,
  22157. programsSize: 0,
  22158. readbackBuffers: 0,
  22159. readbackBuffersSize: 0,
  22160. renderTargets: 0,
  22161. storageAttributes: 0,
  22162. storageAttributesSize: 0,
  22163. textures: 0,
  22164. texturesSize: 0,
  22165. uniformBuffers: 0,
  22166. uniformBuffersSize: 0,
  22167. total: 0
  22168. };
  22169. /**
  22170. * Map for storing calculated byte sizes of tracked objects.
  22171. *
  22172. * @type {Map<Object, number>}
  22173. * @private
  22174. */
  22175. this.memoryMap = new Map();
  22176. }
  22177. /**
  22178. * This method should be executed per draw call and updates the corresponding metrics.
  22179. *
  22180. * @param {Object3D} object - The 3D object that is going to be rendered.
  22181. * @param {number} count - The vertex or index count.
  22182. * @param {number} instanceCount - The instance count.
  22183. */
  22184. update( object, count, instanceCount ) {
  22185. this.render.drawCalls ++;
  22186. if ( object.isMesh || object.isSprite ) {
  22187. this.render.triangles += instanceCount * ( count / 3 );
  22188. } else if ( object.isPoints ) {
  22189. this.render.points += instanceCount * count;
  22190. } else if ( object.isLineSegments ) {
  22191. this.render.lines += instanceCount * ( count / 2 );
  22192. } else if ( object.isLine ) {
  22193. this.render.lines += instanceCount * ( count - 1 );
  22194. } else {
  22195. error( 'WebGPUInfo: Unknown object type.' );
  22196. }
  22197. }
  22198. /**
  22199. * Resets frame related metrics.
  22200. */
  22201. reset() {
  22202. this.render.drawCalls = 0;
  22203. this.render.frameCalls = 0;
  22204. this.compute.frameCalls = 0;
  22205. this.render.triangles = 0;
  22206. this.render.points = 0;
  22207. this.render.lines = 0;
  22208. }
  22209. /**
  22210. * Performs a complete reset of the object.
  22211. */
  22212. dispose() {
  22213. this.reset();
  22214. this.calls = 0;
  22215. this.render.calls = 0;
  22216. this.compute.calls = 0;
  22217. this.render.timestamp = 0;
  22218. this.compute.timestamp = 0;
  22219. for ( const prop in this.memory ) {
  22220. this.memory[ prop ] = 0;
  22221. }
  22222. this.memoryMap.clear();
  22223. }
  22224. /**
  22225. * Tracks texture memory explicitly, updating counts and byte tracking.
  22226. *
  22227. * @param {Texture} texture
  22228. */
  22229. createTexture( texture ) {
  22230. const size = this._getTextureMemorySize( texture );
  22231. this.memoryMap.set( texture, size );
  22232. this.memory.textures ++;
  22233. this.memory.total += size;
  22234. this.memory.texturesSize += size;
  22235. }
  22236. /**
  22237. * Tracks texture memory explicitly, updating counts and byte tracking.
  22238. *
  22239. * @param {Texture} texture
  22240. */
  22241. destroyTexture( texture ) {
  22242. const size = this.memoryMap.get( texture ) || 0;
  22243. this.memoryMap.delete( texture );
  22244. this.memory.textures --;
  22245. this.memory.total -= size;
  22246. this.memory.texturesSize -= size;
  22247. }
  22248. /**
  22249. * Tracks attribute memory explicitly, updating counts and byte tracking.
  22250. *
  22251. * @param {BufferAttribute} attribute
  22252. * @param {string} type - type of attribute
  22253. * @private
  22254. */
  22255. _createAttribute( attribute, type ) {
  22256. const size = this._getAttributeMemorySize( attribute );
  22257. this.memoryMap.set( attribute, { size, type } );
  22258. this.memory[ type ] ++;
  22259. this.memory.total += size;
  22260. this.memory[ type + 'Size' ] += size;
  22261. }
  22262. /**
  22263. * Tracks a regular attribute memory explicitly.
  22264. *
  22265. * @param {BufferAttribute} attribute - The attribute to track.
  22266. */
  22267. createAttribute( attribute ) {
  22268. this._createAttribute( attribute, 'attributes' );
  22269. }
  22270. /**
  22271. * Tracks an index attribute memory explicitly.
  22272. *
  22273. * @param {BufferAttribute} attribute - The index attribute to track.
  22274. */
  22275. createIndexAttribute( attribute ) {
  22276. this._createAttribute( attribute, 'indexAttributes' );
  22277. }
  22278. /**
  22279. * Tracks a storage attribute memory explicitly.
  22280. *
  22281. * @param {BufferAttribute} attribute - The storage attribute to track.
  22282. */
  22283. createStorageAttribute( attribute ) {
  22284. this._createAttribute( attribute, 'storageAttributes' );
  22285. }
  22286. /**
  22287. * Tracks an indirect storage attribute memory explicitly.
  22288. *
  22289. * @param {BufferAttribute} attribute - The indirect storage attribute to track.
  22290. */
  22291. createIndirectStorageAttribute( attribute ) {
  22292. this._createAttribute( attribute, 'indirectStorageAttributes' );
  22293. }
  22294. /**
  22295. * Tracks attribute memory explicitly, updating counts and byte tracking.
  22296. *
  22297. * @param {BufferAttribute} attribute
  22298. */
  22299. destroyAttribute( attribute ) {
  22300. const data = this.memoryMap.get( attribute );
  22301. if ( data ) {
  22302. this.memoryMap.delete( attribute );
  22303. this.memory[ data.type ] --;
  22304. this.memory.total -= data.size;
  22305. this.memory[ data.type + 'Size' ] -= data.size;
  22306. }
  22307. }
  22308. /**
  22309. * Tracks a readback buffer memory explicitly.
  22310. *
  22311. * @param {ReadbackBuffer} readbackBuffer - The readback buffer to track.
  22312. */
  22313. createReadbackBuffer( readbackBuffer ) {
  22314. const maxByteLength = readbackBuffer.maxByteLength;
  22315. this.memoryMap.set( readbackBuffer, { size: maxByteLength, type: 'readbackBuffers' } );
  22316. this.memory.readbackBuffers ++;
  22317. this.memory.total += maxByteLength;
  22318. this.memory.readbackBuffersSize += maxByteLength;
  22319. }
  22320. /**
  22321. * Tracks a readback buffer memory explicitly.
  22322. *
  22323. * @param {ReadbackBuffer} readbackBuffer - The readback buffer to track.
  22324. */
  22325. destroyReadbackBuffer( readbackBuffer ) {
  22326. const { size } = this.memoryMap.get( readbackBuffer );
  22327. this.memoryMap.delete( readbackBuffer );
  22328. this.memory.readbackBuffers --;
  22329. this.memory.total -= size;
  22330. this.memory.readbackBuffersSize -= size;
  22331. }
  22332. /**
  22333. * Tracks a uniform buffer memory explicitly.
  22334. *
  22335. * @param {UniformBuffer} uniformBuffer - The uniform buffer to track.
  22336. */
  22337. createUniformBuffer( uniformBuffer ) {
  22338. const size = uniformBuffer.byteLength;
  22339. this.memoryMap.set( uniformBuffer, { size, type: 'uniformBuffers' } );
  22340. this.memory.uniformBuffers ++;
  22341. this.memory.total += size;
  22342. this.memory.uniformBuffersSize += size;
  22343. }
  22344. /**
  22345. * Tracks a uniform buffer memory explicitly.
  22346. *
  22347. * @param {UniformBuffer} uniformBuffer - The uniform buffer to track.
  22348. */
  22349. destroyUniformBuffer( uniformBuffer ) {
  22350. const data = this.memoryMap.get( uniformBuffer );
  22351. if ( data ) {
  22352. this.memoryMap.delete( uniformBuffer );
  22353. this.memory.uniformBuffers --;
  22354. this.memory.total -= data.size;
  22355. this.memory.uniformBuffersSize -= data.size;
  22356. }
  22357. }
  22358. /**
  22359. * Tracks program memory explicitly, updating counts and byte tracking.
  22360. *
  22361. * @param {ProgrammableStage} program - The program to track.
  22362. */
  22363. createProgram( program ) {
  22364. const size = program.code.length; // Approx size
  22365. this.memoryMap.set( program, size );
  22366. this.memory.programs ++;
  22367. this.memory.total += size;
  22368. this.memory.programsSize += size;
  22369. }
  22370. /**
  22371. * Tracks program memory explicitly, updating counts and byte tracking.
  22372. *
  22373. * @param {Object} program - The program to track.
  22374. */
  22375. destroyProgram( program ) {
  22376. const size = this.memoryMap.get( program ) || 0;
  22377. this.memoryMap.delete( program );
  22378. this.memory.programs --;
  22379. this.memory.total -= size;
  22380. this.memory.programsSize -= size;
  22381. }
  22382. /**
  22383. * Calculates the memory size of a texture in bytes.
  22384. *
  22385. * @param {Texture} texture - The texture to calculate the size for.
  22386. * @return {number} The calculated size in bytes.
  22387. * @private
  22388. */
  22389. _getTextureMemorySize( texture ) {
  22390. if ( texture.isCompressedTexture ) {
  22391. return 1; // Fallback estimate since exact format decompressed isn't readily available without format maps
  22392. }
  22393. let bytesPerChannel = 1;
  22394. if ( texture.type === ByteType || texture.type === UnsignedByteType ) bytesPerChannel = 1;
  22395. else if ( texture.type === ShortType || texture.type === UnsignedShortType || texture.type === HalfFloatType ) bytesPerChannel = 2;
  22396. else if ( texture.type === IntType || texture.type === UnsignedIntType || texture.type === FloatType ) bytesPerChannel = 4;
  22397. let channels = 4; // RGBA default
  22398. if ( texture.format === AlphaFormat || texture.format === RedFormat || texture.format === RedIntegerFormat || texture.format === DepthFormat || texture.format === DepthStencilFormat ) channels = 1;
  22399. else if ( texture.format === RGFormat || texture.format === RGIntegerFormat ) channels = 2;
  22400. else if ( texture.format === RGBFormat || texture.format === RGBIntegerFormat ) channels = 3;
  22401. let bytesPerPixel = bytesPerChannel * channels;
  22402. // Packed overrides
  22403. if ( texture.type === UnsignedShort4444Type || texture.type === UnsignedShort5551Type ) bytesPerPixel = 2;
  22404. else if ( texture.type === UnsignedInt248Type || texture.type === UnsignedInt5999Type || texture.type === UnsignedInt101111Type ) bytesPerPixel = 4;
  22405. const width = texture.width || 1;
  22406. const height = texture.height || 1;
  22407. const depth = texture.isCubeTexture ? 6 : ( texture.depth || 1 );
  22408. let size = width * height * depth * bytesPerPixel;
  22409. const mipmaps = texture.mipmaps;
  22410. if ( mipmaps && mipmaps.length > 0 ) {
  22411. let mipmapSize = 0;
  22412. for ( let i = 0; i < mipmaps.length; i ++ ) {
  22413. const mipmap = mipmaps[ i ];
  22414. if ( mipmap.data ) {
  22415. mipmapSize += mipmap.data.byteLength;
  22416. } else {
  22417. const mipWidth = mipmap.width || Math.max( 1, width >> i );
  22418. const mipHeight = mipmap.height || Math.max( 1, height >> i );
  22419. mipmapSize += mipWidth * mipHeight * depth * bytesPerPixel;
  22420. }
  22421. }
  22422. size += mipmapSize;
  22423. } else if ( texture.generateMipmaps ) {
  22424. size = size * 1.333; // MiP chain approximation
  22425. }
  22426. return Math.round( size );
  22427. }
  22428. /**
  22429. * Calculates the memory size of an attribute in bytes.
  22430. *
  22431. * @param {BufferAttribute} attribute - The attribute to calculate the size for.
  22432. * @return {number} The calculated size in bytes.
  22433. * @private
  22434. */
  22435. _getAttributeMemorySize( attribute ) {
  22436. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  22437. if ( attribute.array ) {
  22438. return attribute.array.byteLength;
  22439. } else if ( attribute.count && attribute.itemSize ) {
  22440. return attribute.count * attribute.itemSize * 4; // Assume Float32
  22441. }
  22442. return 0;
  22443. }
  22444. }
  22445. /**
  22446. * Abstract class for representing pipelines.
  22447. *
  22448. * @private
  22449. * @abstract
  22450. */
  22451. class Pipeline {
  22452. /**
  22453. * Constructs a new pipeline.
  22454. *
  22455. * @param {string} cacheKey - The pipeline's cache key.
  22456. */
  22457. constructor( cacheKey ) {
  22458. /**
  22459. * The pipeline's cache key.
  22460. *
  22461. * @type {string}
  22462. */
  22463. this.cacheKey = cacheKey;
  22464. /**
  22465. * How often the pipeline is currently in use.
  22466. *
  22467. * @type {number}
  22468. * @default 0
  22469. */
  22470. this.usedTimes = 0;
  22471. }
  22472. }
  22473. /**
  22474. * Class for representing render pipelines.
  22475. *
  22476. * @private
  22477. * @augments Pipeline
  22478. */
  22479. class RenderObjectPipeline extends Pipeline {
  22480. /**
  22481. * Constructs a new render object pipeline.
  22482. *
  22483. * @param {string} cacheKey - The pipeline's cache key.
  22484. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  22485. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  22486. */
  22487. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  22488. super( cacheKey );
  22489. /**
  22490. * The pipeline's vertex shader.
  22491. *
  22492. * @type {ProgrammableStage}
  22493. */
  22494. this.vertexProgram = vertexProgram;
  22495. /**
  22496. * The pipeline's fragment shader.
  22497. *
  22498. * @type {ProgrammableStage}
  22499. */
  22500. this.fragmentProgram = fragmentProgram;
  22501. }
  22502. }
  22503. /**
  22504. * Class for representing compute pipelines.
  22505. *
  22506. * @private
  22507. * @augments Pipeline
  22508. */
  22509. class ComputePipeline extends Pipeline {
  22510. /**
  22511. * Constructs a new compute pipeline.
  22512. *
  22513. * @param {string} cacheKey - The pipeline's cache key.
  22514. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  22515. */
  22516. constructor( cacheKey, computeProgram ) {
  22517. super( cacheKey );
  22518. /**
  22519. * The pipeline's compute shader.
  22520. *
  22521. * @type {ProgrammableStage}
  22522. */
  22523. this.computeProgram = computeProgram;
  22524. /**
  22525. * This flag can be used for type testing.
  22526. *
  22527. * @type {boolean}
  22528. * @readonly
  22529. * @default true
  22530. */
  22531. this.isComputePipeline = true;
  22532. }
  22533. }
  22534. let _id$9 = 0;
  22535. /**
  22536. * Class for representing programmable stages which are vertex,
  22537. * fragment or compute shaders. Unlike fixed-function states (like blending),
  22538. * they represent the programmable part of a pipeline.
  22539. *
  22540. * @private
  22541. */
  22542. class ProgrammableStage {
  22543. /**
  22544. * Constructs a new programmable stage.
  22545. *
  22546. * @param {string} code - The shader code.
  22547. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  22548. * @param {string} name - The name of the shader.
  22549. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  22550. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  22551. */
  22552. constructor( code, stage, name, transforms = null, attributes = null ) {
  22553. /**
  22554. * The id of the programmable stage.
  22555. *
  22556. * @type {number}
  22557. */
  22558. this.id = _id$9 ++;
  22559. /**
  22560. * The shader code.
  22561. *
  22562. * @type {string}
  22563. */
  22564. this.code = code;
  22565. /**
  22566. * The type of stage.
  22567. *
  22568. * @type {string}
  22569. */
  22570. this.stage = stage;
  22571. /**
  22572. * The name of the stage.
  22573. * This is used for debugging purposes.
  22574. *
  22575. * @type {string}
  22576. */
  22577. this.name = name;
  22578. /**
  22579. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  22580. *
  22581. * @type {?Array<Object>}
  22582. */
  22583. this.transforms = transforms;
  22584. /**
  22585. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  22586. *
  22587. * @type {?Array<Object>}
  22588. */
  22589. this.attributes = attributes;
  22590. /**
  22591. * How often the programmable stage is currently in use.
  22592. *
  22593. * @type {number}
  22594. * @default 0
  22595. */
  22596. this.usedTimes = 0;
  22597. }
  22598. }
  22599. /**
  22600. * This renderer module manages the pipelines of the renderer.
  22601. *
  22602. * @private
  22603. * @augments DataMap
  22604. */
  22605. class Pipelines extends DataMap {
  22606. /**
  22607. * Constructs a new pipeline management component.
  22608. *
  22609. * @param {Backend} backend - The renderer's backend.
  22610. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  22611. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22612. */
  22613. constructor( backend, nodes, info ) {
  22614. super();
  22615. /**
  22616. * The renderer's backend.
  22617. *
  22618. * @type {Backend}
  22619. */
  22620. this.backend = backend;
  22621. /**
  22622. * Renderer component for managing nodes related logic.
  22623. *
  22624. * @type {NodeManager}
  22625. */
  22626. this.nodes = nodes;
  22627. /**
  22628. * Renderer component for managing metrics and monitoring data.
  22629. *
  22630. * @type {Info}
  22631. */
  22632. this.info = info;
  22633. /**
  22634. * A references to the bindings management component.
  22635. * This reference will be set inside the `Bindings`
  22636. * constructor.
  22637. *
  22638. * @type {?Bindings}
  22639. * @default null
  22640. */
  22641. this.bindings = null;
  22642. /**
  22643. * Internal cache for maintaining pipelines.
  22644. * The key of the map is a cache key, the value the pipeline.
  22645. *
  22646. * @type {Map<string,Pipeline>}
  22647. */
  22648. this.caches = new Map();
  22649. /**
  22650. * This dictionary maintains for each shader stage type (vertex,
  22651. * fragment and compute) the programmable stage objects which
  22652. * represent the actual shader code.
  22653. *
  22654. * @type {Object<string,Map<string, ProgrammableStage>>}
  22655. */
  22656. this.programs = {
  22657. vertex: new Map(),
  22658. fragment: new Map(),
  22659. compute: new Map()
  22660. };
  22661. }
  22662. /**
  22663. * Returns a compute pipeline for the given compute node.
  22664. *
  22665. * @param {Node} computeNode - The compute node.
  22666. * @param {Array<BindGroup>} bindings - The bindings.
  22667. * @return {ComputePipeline} The compute pipeline.
  22668. */
  22669. getForCompute( computeNode, bindings ) {
  22670. const { backend } = this;
  22671. const data = this.get( computeNode );
  22672. if ( this._needsComputeUpdate( computeNode ) ) {
  22673. const previousPipeline = data.pipeline;
  22674. if ( previousPipeline ) {
  22675. previousPipeline.usedTimes --;
  22676. previousPipeline.computeProgram.usedTimes --;
  22677. }
  22678. // get shader
  22679. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  22680. // programmable stage
  22681. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  22682. if ( stageCompute === undefined ) {
  22683. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  22684. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  22685. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  22686. backend.createProgram( stageCompute );
  22687. this.info.createProgram( stageCompute );
  22688. }
  22689. // determine compute pipeline
  22690. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  22691. let pipeline = this.caches.get( cacheKey );
  22692. if ( pipeline === undefined ) {
  22693. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22694. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  22695. }
  22696. // keep track of all used times
  22697. pipeline.usedTimes ++;
  22698. stageCompute.usedTimes ++;
  22699. //
  22700. data.version = computeNode.version;
  22701. data.pipeline = pipeline;
  22702. }
  22703. return data.pipeline;
  22704. }
  22705. /**
  22706. * Returns a render pipeline for the given render object.
  22707. *
  22708. * @param {RenderObject} renderObject - The render object.
  22709. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  22710. * @return {RenderObjectPipeline} The render pipeline.
  22711. */
  22712. getForRender( renderObject, promises = null ) {
  22713. const { backend } = this;
  22714. const data = this.get( renderObject );
  22715. if ( this._needsRenderUpdate( renderObject ) ) {
  22716. const previousPipeline = data.pipeline;
  22717. if ( previousPipeline ) {
  22718. previousPipeline.usedTimes --;
  22719. previousPipeline.vertexProgram.usedTimes --;
  22720. previousPipeline.fragmentProgram.usedTimes --;
  22721. }
  22722. // get shader
  22723. const nodeBuilderState = renderObject.getNodeBuilderState();
  22724. const name = renderObject.material ? renderObject.material.name : '';
  22725. // programmable stages
  22726. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  22727. if ( stageVertex === undefined ) {
  22728. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  22729. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  22730. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  22731. backend.createProgram( stageVertex );
  22732. this.info.createProgram( stageVertex );
  22733. }
  22734. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  22735. if ( stageFragment === undefined ) {
  22736. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  22737. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  22738. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  22739. backend.createProgram( stageFragment );
  22740. this.info.createProgram( stageFragment );
  22741. }
  22742. // determine render pipeline
  22743. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22744. let pipeline = this.caches.get( cacheKey );
  22745. if ( pipeline === undefined ) {
  22746. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22747. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  22748. } else {
  22749. renderObject.pipeline = pipeline;
  22750. }
  22751. // keep track of all used times
  22752. pipeline.usedTimes ++;
  22753. stageVertex.usedTimes ++;
  22754. stageFragment.usedTimes ++;
  22755. //
  22756. data.pipeline = pipeline;
  22757. }
  22758. return data.pipeline;
  22759. }
  22760. /**
  22761. * Checks if the render pipeline for the given render object is ready for drawing.
  22762. * Returns false if the GPU pipeline is still being compiled asynchronously.
  22763. *
  22764. * @param {RenderObject} renderObject - The render object.
  22765. * @return {boolean} True if the pipeline is ready for drawing.
  22766. */
  22767. isReady( renderObject ) {
  22768. const data = this.get( renderObject );
  22769. const pipeline = data.pipeline;
  22770. if ( pipeline === undefined ) return false;
  22771. const pipelineData = this.backend.get( pipeline );
  22772. return pipelineData.pipeline !== undefined && pipelineData.pipeline !== null;
  22773. }
  22774. /**
  22775. * Deletes the pipeline for the given render object.
  22776. *
  22777. * @param {RenderObject} object - The render object.
  22778. * @return {?Object} The deleted dictionary.
  22779. */
  22780. delete( object ) {
  22781. const pipeline = this.get( object ).pipeline;
  22782. if ( pipeline ) {
  22783. // pipeline
  22784. pipeline.usedTimes --;
  22785. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  22786. // programs
  22787. if ( pipeline.isComputePipeline ) {
  22788. pipeline.computeProgram.usedTimes --;
  22789. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  22790. } else {
  22791. pipeline.fragmentProgram.usedTimes --;
  22792. pipeline.vertexProgram.usedTimes --;
  22793. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  22794. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  22795. }
  22796. }
  22797. return super.delete( object );
  22798. }
  22799. /**
  22800. * Frees internal resources.
  22801. */
  22802. dispose() {
  22803. super.dispose();
  22804. this.caches = new Map();
  22805. this.programs = {
  22806. vertex: new Map(),
  22807. fragment: new Map(),
  22808. compute: new Map()
  22809. };
  22810. }
  22811. /**
  22812. * Updates the pipeline for the given render object.
  22813. *
  22814. * @param {RenderObject} renderObject - The render object.
  22815. */
  22816. updateForRender( renderObject ) {
  22817. this.getForRender( renderObject );
  22818. }
  22819. /**
  22820. * Returns a compute pipeline for the given parameters.
  22821. *
  22822. * @private
  22823. * @param {Node} computeNode - The compute node.
  22824. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  22825. * @param {string} cacheKey - The cache key.
  22826. * @param {Array<BindGroup>} bindings - The bindings.
  22827. * @return {ComputePipeline} The compute pipeline.
  22828. */
  22829. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  22830. // check for existing pipeline
  22831. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  22832. let pipeline = this.caches.get( cacheKey );
  22833. if ( pipeline === undefined ) {
  22834. pipeline = new ComputePipeline( cacheKey, stageCompute );
  22835. this.caches.set( cacheKey, pipeline );
  22836. this.backend.createComputePipeline( pipeline, bindings );
  22837. }
  22838. return pipeline;
  22839. }
  22840. /**
  22841. * Returns a render pipeline for the given parameters.
  22842. *
  22843. * @private
  22844. * @param {RenderObject} renderObject - The render object.
  22845. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  22846. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  22847. * @param {string} cacheKey - The cache key.
  22848. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  22849. * @return {RenderObjectPipeline} The render pipeline.
  22850. */
  22851. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  22852. // check for existing pipeline
  22853. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22854. let pipeline = this.caches.get( cacheKey );
  22855. if ( pipeline === undefined ) {
  22856. pipeline = new RenderObjectPipeline( cacheKey, stageVertex, stageFragment );
  22857. this.caches.set( cacheKey, pipeline );
  22858. renderObject.pipeline = pipeline;
  22859. // The `promises` array is `null` by default and only set to an empty array when
  22860. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  22861. // pending promises that resolve when the render pipelines are ready for rendering.
  22862. this.backend.createRenderPipeline( renderObject, promises );
  22863. }
  22864. return pipeline;
  22865. }
  22866. /**
  22867. * Computes a cache key representing a compute pipeline.
  22868. *
  22869. * @private
  22870. * @param {Node} computeNode - The compute node.
  22871. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  22872. * @return {string} The cache key.
  22873. */
  22874. _getComputeCacheKey( computeNode, stageCompute ) {
  22875. return computeNode.id + ',' + stageCompute.id;
  22876. }
  22877. /**
  22878. * Computes a cache key representing a render pipeline.
  22879. *
  22880. * @private
  22881. * @param {RenderObject} renderObject - The render object.
  22882. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  22883. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  22884. * @return {string} The cache key.
  22885. */
  22886. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  22887. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  22888. }
  22889. /**
  22890. * Releases the given pipeline.
  22891. *
  22892. * @private
  22893. * @param {Pipeline} pipeline - The pipeline to release.
  22894. */
  22895. _releasePipeline( pipeline ) {
  22896. this.caches.delete( pipeline.cacheKey );
  22897. }
  22898. /**
  22899. * Releases the shader program.
  22900. *
  22901. * @private
  22902. * @param {Object} program - The shader program to release.
  22903. */
  22904. _releaseProgram( program ) {
  22905. const code = program.code;
  22906. const stage = program.stage;
  22907. this.programs[ stage ].delete( code );
  22908. this.info.destroyProgram( program );
  22909. }
  22910. /**
  22911. * Returns `true` if the compute pipeline for the given compute node requires an update.
  22912. *
  22913. * @private
  22914. * @param {Node} computeNode - The compute node.
  22915. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  22916. */
  22917. _needsComputeUpdate( computeNode ) {
  22918. const data = this.get( computeNode );
  22919. return data.pipeline === undefined || data.version !== computeNode.version;
  22920. }
  22921. /**
  22922. * Returns `true` if the render pipeline for the given render object requires an update.
  22923. *
  22924. * @private
  22925. * @param {RenderObject} renderObject - The render object.
  22926. * @return {boolean} Whether the render object for the given render object requires an update or not.
  22927. */
  22928. _needsRenderUpdate( renderObject ) {
  22929. const data = this.get( renderObject );
  22930. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  22931. }
  22932. }
  22933. /**
  22934. * This renderer module manages the bindings of the renderer.
  22935. *
  22936. * @private
  22937. * @augments DataMap
  22938. */
  22939. class Bindings extends DataMap {
  22940. /**
  22941. * Constructs a new bindings management component.
  22942. *
  22943. * @param {Backend} backend - The renderer's backend.
  22944. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  22945. * @param {Textures} textures - Renderer component for managing textures.
  22946. * @param {Attributes} attributes - Renderer component for managing attributes.
  22947. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  22948. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22949. */
  22950. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  22951. super();
  22952. /**
  22953. * The renderer's backend.
  22954. *
  22955. * @type {Backend}
  22956. */
  22957. this.backend = backend;
  22958. /**
  22959. * Renderer component for managing textures.
  22960. *
  22961. * @type {Textures}
  22962. */
  22963. this.textures = textures;
  22964. /**
  22965. * Renderer component for managing pipelines.
  22966. *
  22967. * @type {Pipelines}
  22968. */
  22969. this.pipelines = pipelines;
  22970. /**
  22971. * Renderer component for managing attributes.
  22972. *
  22973. * @type {Attributes}
  22974. */
  22975. this.attributes = attributes;
  22976. /**
  22977. * Renderer component for managing nodes related logic.
  22978. *
  22979. * @type {NodeManager}
  22980. */
  22981. this.nodes = nodes;
  22982. /**
  22983. * Renderer component for managing metrics and monitoring data.
  22984. *
  22985. * @type {Info}
  22986. */
  22987. this.info = info;
  22988. this.pipelines.bindings = this; // assign bindings to pipelines
  22989. }
  22990. /**
  22991. * Returns the bind groups for the given render object.
  22992. *
  22993. * @param {RenderObject} renderObject - The render object.
  22994. * @return {Array<BindGroup>} The bind groups.
  22995. */
  22996. getForRender( renderObject ) {
  22997. const bindings = renderObject.getBindings();
  22998. const renderObjectData = this.get( renderObject );
  22999. if ( renderObjectData.initialized !== true ) {
  23000. // bind groups are created once per object
  23001. this._createBindings( bindings );
  23002. renderObjectData.initialized = true;
  23003. }
  23004. return bindings;
  23005. }
  23006. /**
  23007. * Returns the bind groups for the given compute node.
  23008. *
  23009. * @param {Node} computeNode - The compute node.
  23010. * @return {Array<BindGroup>} The bind groups.
  23011. */
  23012. getForCompute( computeNode ) {
  23013. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  23014. const computeNodeData = this.get( computeNode );
  23015. if ( computeNodeData.initialized !== true || computeNodeData.bindings !== bindings ) {
  23016. // bind groups are created once per compute node version
  23017. if ( computeNodeData.bindings !== undefined ) {
  23018. this._destroyBindings( computeNodeData.bindings );
  23019. }
  23020. this._createBindings( bindings );
  23021. computeNodeData.initialized = true;
  23022. computeNodeData.bindings = bindings;
  23023. }
  23024. return bindings;
  23025. }
  23026. /**
  23027. * Updates the bindings for the given compute node.
  23028. *
  23029. * @param {Node} computeNode - The compute node.
  23030. */
  23031. updateForCompute( computeNode ) {
  23032. this._updateBindings( this.getForCompute( computeNode ) );
  23033. }
  23034. /**
  23035. * Updates the bindings for the given render object.
  23036. *
  23037. * @param {RenderObject} renderObject - The render object.
  23038. */
  23039. updateForRender( renderObject ) {
  23040. this._updateBindings( this.getForRender( renderObject ) );
  23041. }
  23042. /**
  23043. * Deletes the bindings for the given compute node.
  23044. *
  23045. * @param {Node} computeNode - The compute node.
  23046. */
  23047. deleteForCompute( computeNode ) {
  23048. const computeNodeData = this.get( computeNode );
  23049. const bindings = computeNodeData.bindings || this.nodes.getForCompute( computeNode ).bindings;
  23050. this._destroyBindings( bindings );
  23051. this.delete( computeNode );
  23052. }
  23053. /**
  23054. * Deletes the bindings for the given renderObject node.
  23055. *
  23056. * @param {RenderObject} renderObject - The renderObject.
  23057. */
  23058. deleteForRender( renderObject ) {
  23059. const bindings = renderObject.getBindings();
  23060. this._destroyBindings( bindings );
  23061. this.delete( renderObject );
  23062. }
  23063. /**
  23064. * Creates the bindings for the given array of bindings.
  23065. *
  23066. * @param {Array<BindGroup>} bindings - The bind groups.
  23067. */
  23068. _createBindings( bindings ) {
  23069. for ( const bindGroup of bindings ) {
  23070. // binding group
  23071. const groupData = this.get( bindGroup );
  23072. if ( groupData.bindGroup === undefined ) {
  23073. // initialize
  23074. for ( const binding of bindGroup.bindings ) {
  23075. if ( binding.isUniformBuffer ) {
  23076. this.backend.createUniformBuffer( binding );
  23077. this.info.createUniformBuffer( binding );
  23078. } else if ( binding.isSampledTexture ) {
  23079. this.textures.updateTexture( binding.texture );
  23080. } else if ( binding.isSampler ) {
  23081. this.textures.updateSampler( binding.texture, binding.textureNode );
  23082. } else if ( binding.isStorageBuffer ) {
  23083. const attribute = binding.attribute;
  23084. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  23085. this.attributes.update( attribute, attributeType );
  23086. }
  23087. }
  23088. // each object defines an array of bindings (ubos, textures, samplers etc.)
  23089. this.backend.createBindings( bindGroup, bindings, 0 );
  23090. groupData.bindGroup = bindGroup;
  23091. groupData.usedTimes = 1;
  23092. } else {
  23093. groupData.usedTimes ++;
  23094. }
  23095. }
  23096. }
  23097. /**
  23098. * Deletes the given array of bindings.
  23099. *
  23100. * @param {Array<BindGroup>} bindings - The bind groups.
  23101. */
  23102. _destroyBindings( bindings ) {
  23103. for ( const bindGroup of bindings ) {
  23104. const groupData = this.get( bindGroup );
  23105. groupData.usedTimes --;
  23106. if ( groupData.usedTimes === 0 ) {
  23107. for ( const binding of bindGroup.bindings ) {
  23108. if ( binding.isUniformBuffer ) {
  23109. this.backend.destroyUniformBuffer( binding );
  23110. this.info.destroyUniformBuffer( binding );
  23111. // release arrays
  23112. binding.release();
  23113. } else if ( binding.isSampler ) {
  23114. binding.release();
  23115. }
  23116. }
  23117. this.backend.deleteBindGroupData( bindGroup );
  23118. this.delete( bindGroup );
  23119. }
  23120. }
  23121. }
  23122. /**
  23123. * Updates the given array of bindings.
  23124. *
  23125. * @param {Array<BindGroup>} bindings - The bind groups.
  23126. */
  23127. _updateBindings( bindings ) {
  23128. for ( const bindGroup of bindings ) {
  23129. this._update( bindGroup, bindings );
  23130. }
  23131. }
  23132. /**
  23133. * Updates the given bind group.
  23134. *
  23135. * @param {BindGroup} bindGroup - The bind group to update.
  23136. * @param {Array<BindGroup>} bindings - The bind groups.
  23137. */
  23138. _update( bindGroup, bindings ) {
  23139. const { backend } = this;
  23140. let needsBindingsUpdate = false;
  23141. let cacheBindings = true;
  23142. let cacheIndex = 0;
  23143. let version = 0;
  23144. // iterate over all bindings and check if buffer updates or a new binding group is required
  23145. for ( const binding of bindGroup.bindings ) {
  23146. const updatedGroup = this.nodes.updateGroup( binding );
  23147. // every uniforms group is a uniform buffer. So if no update is required,
  23148. // we move one with the next binding. Otherwise the next if block will update the group.
  23149. if ( updatedGroup === false ) continue;
  23150. //
  23151. if ( binding.isStorageBuffer ) {
  23152. const attribute = binding.attribute;
  23153. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  23154. const bindingData = backend.get( binding );
  23155. this.attributes.update( attribute, attributeType );
  23156. if ( bindingData.attribute !== attribute ) {
  23157. bindingData.attribute = attribute;
  23158. needsBindingsUpdate = true;
  23159. }
  23160. }
  23161. if ( binding.isUniformBuffer ) {
  23162. const updated = binding.update();
  23163. if ( updated ) {
  23164. backend.updateBinding( binding );
  23165. }
  23166. } else if ( binding.isSampledTexture ) {
  23167. const updated = binding.update();
  23168. // get the texture data after the update, to sync the texture reference from node
  23169. const texture = binding.texture;
  23170. const texturesTextureData = this.textures.get( texture );
  23171. if ( updated ) {
  23172. // version: update the texture data or create a new one
  23173. this.textures.updateTexture( texture );
  23174. // generation: update the bindings if the binding refers to a different texture object
  23175. if ( binding.generation !== texturesTextureData.generation ) {
  23176. binding.generation = texturesTextureData.generation;
  23177. needsBindingsUpdate = true;
  23178. }
  23179. // keep track which bind groups refer to the current texture (this is needed for dispose)
  23180. texturesTextureData.bindGroups.add( bindGroup );
  23181. }
  23182. const textureData = backend.get( texture );
  23183. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  23184. cacheBindings = false;
  23185. } else {
  23186. cacheIndex = cacheIndex * 10 + texture.id;
  23187. version += texture.version;
  23188. }
  23189. if ( texture.isStorageTexture === true && texture.mipmapsAutoUpdate === true ) {
  23190. const textureData = this.get( texture );
  23191. if ( binding.store === true ) {
  23192. textureData.needsMipmap = true;
  23193. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  23194. this.backend.generateMipmaps( texture );
  23195. textureData.needsMipmap = false;
  23196. }
  23197. }
  23198. } else if ( binding.isSampler ) {
  23199. const updated = binding.update();
  23200. if ( updated ) {
  23201. const samplerKey = this.textures.updateSampler( binding.texture, binding.textureNode );
  23202. if ( binding.samplerKey !== samplerKey ) {
  23203. binding.samplerKey = samplerKey;
  23204. needsBindingsUpdate = true;
  23205. }
  23206. }
  23207. }
  23208. if ( binding.isBuffer && binding.updateRanges.length > 0 ) {
  23209. binding.clearUpdateRanges();
  23210. }
  23211. }
  23212. if ( needsBindingsUpdate === true ) {
  23213. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  23214. }
  23215. }
  23216. }
  23217. const _emptyArray = /*@__PURE__*/ Object.freeze( [] );
  23218. /**
  23219. * Default sorting function for opaque render items.
  23220. *
  23221. * @private
  23222. * @function
  23223. * @param {Object} a - The first render item.
  23224. * @param {Object} b - The second render item.
  23225. * @return {number} A numeric value which defines the sort order.
  23226. */
  23227. function painterSortStable( a, b ) {
  23228. if ( a.groupOrder !== b.groupOrder ) {
  23229. return a.groupOrder - b.groupOrder;
  23230. } else if ( a.renderOrder !== b.renderOrder ) {
  23231. return a.renderOrder - b.renderOrder;
  23232. } else if ( a.z !== b.z ) {
  23233. return a.z - b.z;
  23234. } else {
  23235. return a.id - b.id;
  23236. }
  23237. }
  23238. /**
  23239. * Default sorting function for transparent render items.
  23240. *
  23241. * @private
  23242. * @function
  23243. * @param {Object} a - The first render item.
  23244. * @param {Object} b - The second render item.
  23245. * @return {number} A numeric value which defines the sort order.
  23246. */
  23247. function reversePainterSortStable( a, b ) {
  23248. if ( a.groupOrder !== b.groupOrder ) {
  23249. return a.groupOrder - b.groupOrder;
  23250. } else if ( a.renderOrder !== b.renderOrder ) {
  23251. return a.renderOrder - b.renderOrder;
  23252. } else if ( a.z !== b.z ) {
  23253. return b.z - a.z;
  23254. } else {
  23255. return a.id - b.id;
  23256. }
  23257. }
  23258. /**
  23259. * Returns `true` if the given transparent material requires a double pass.
  23260. *
  23261. * @private
  23262. * @function
  23263. * @param {Material} material - The transparent material.
  23264. * @return {boolean} Whether the given material requires a double pass or not.
  23265. */
  23266. function needsDoublePass( material ) {
  23267. const hasTransmission = material.transmission > 0 || ( material.transmissionNode && material.transmissionNode.isNode );
  23268. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  23269. }
  23270. /**
  23271. * When the renderer analyzes the scene at the beginning of a render call,
  23272. * it stores 3D object for further processing in render lists. Depending on the
  23273. * properties of a 3D objects (like their transformation or material state), the
  23274. * objects are maintained in ordered lists for the actual rendering.
  23275. *
  23276. * Render lists are unique per scene and camera combination.
  23277. *
  23278. * @private
  23279. * @augments Pipeline
  23280. */
  23281. class RenderList {
  23282. /**
  23283. * Constructs a render list.
  23284. *
  23285. * @param {Lighting} lighting - The lighting management component.
  23286. * @param {Scene} scene - The scene.
  23287. * @param {Camera} camera - The camera the scene is rendered with.
  23288. */
  23289. constructor( lighting, scene, camera ) {
  23290. /**
  23291. * 3D objects are transformed into render items and stored in this array.
  23292. *
  23293. * @type {Array<Object>}
  23294. */
  23295. this.renderItems = [];
  23296. /**
  23297. * The current render items index.
  23298. *
  23299. * @type {number}
  23300. * @default 0
  23301. */
  23302. this.renderItemsIndex = 0;
  23303. /**
  23304. * A list with opaque render items.
  23305. *
  23306. * @type {Array<Object>}
  23307. */
  23308. this.opaque = [];
  23309. /**
  23310. * A list with transparent render items which require
  23311. * double pass rendering (e.g. transmissive objects).
  23312. *
  23313. * @type {Array<Object>}
  23314. */
  23315. this.transparentDoublePass = [];
  23316. /**
  23317. * A list with transparent render items.
  23318. *
  23319. * @type {Array<Object>}
  23320. */
  23321. this.transparent = [];
  23322. /**
  23323. * A list with transparent render bundle data.
  23324. *
  23325. * @type {Array<Object>}
  23326. */
  23327. this.bundles = [];
  23328. /**
  23329. * The lighting management component.
  23330. *
  23331. * @type {Lighting}
  23332. */
  23333. this.lighting = lighting;
  23334. /**
  23335. * The render list's lights node. This node is later
  23336. * relevant for the actual analytical light nodes which
  23337. * compute the scene's lighting in the shader.
  23338. *
  23339. * @type {LightsNode}
  23340. */
  23341. this.lightsNode = lighting.getNode( scene );
  23342. /**
  23343. * The scene's lights stored in an array. This array
  23344. * is used to setup the lights node.
  23345. *
  23346. * @type {Array<Light>}
  23347. */
  23348. this.lightsArray = [];
  23349. /**
  23350. * The scene.
  23351. *
  23352. * @type {Scene}
  23353. */
  23354. this.scene = scene;
  23355. /**
  23356. * The camera the scene is rendered with.
  23357. *
  23358. * @type {Camera}
  23359. */
  23360. this.camera = camera;
  23361. /**
  23362. * How many objects perform occlusion query tests.
  23363. *
  23364. * @type {number}
  23365. * @default 0
  23366. */
  23367. this.occlusionQueryCount = 0;
  23368. /**
  23369. * The last object that was counted for occlusion query testing. Used to
  23370. * avoid counting an object more than once when it produces multiple render
  23371. * items (e.g. a mesh with multiple material groups), since such an object
  23372. * is covered by a single occlusion query.
  23373. *
  23374. * @private
  23375. * @type {?Object3D}
  23376. * @default null
  23377. */
  23378. this._lastOcclusionObject = null;
  23379. }
  23380. /**
  23381. * This method is called right at the beginning of a render call
  23382. * before the scene is analyzed. It prepares the internal data
  23383. * structures for the upcoming render lists generation.
  23384. *
  23385. * @return {RenderList} A reference to this render list.
  23386. */
  23387. begin() {
  23388. this.renderItemsIndex = 0;
  23389. this.opaque.length = 0;
  23390. this.transparentDoublePass.length = 0;
  23391. this.transparent.length = 0;
  23392. this.bundles.length = 0;
  23393. this.lightsArray.length = 0;
  23394. this.occlusionQueryCount = 0;
  23395. return this;
  23396. }
  23397. /**
  23398. * Returns a render item for the giving render item state. The state is defined
  23399. * by a series of object-related parameters.
  23400. *
  23401. * The method avoids object creation by holding render items and reusing them in
  23402. * subsequent render calls (just with different property values).
  23403. *
  23404. * @param {Object3D} object - The 3D object.
  23405. * @param {BufferGeometry} geometry - The 3D object's geometry.
  23406. * @param {Material} material - The 3D object's material.
  23407. * @param {number} groupOrder - The current group order.
  23408. * @param {number} z - Th 3D object's depth value (z value in clip space).
  23409. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  23410. * @param {ClippingContext} clippingContext - The current clipping context.
  23411. * @return {Object} The render item.
  23412. */
  23413. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  23414. let renderItem = this.renderItems[ this.renderItemsIndex ];
  23415. if ( renderItem === undefined ) {
  23416. renderItem = {
  23417. id: object.id,
  23418. object: object,
  23419. geometry: geometry,
  23420. material: material,
  23421. groupOrder: groupOrder,
  23422. renderOrder: object.renderOrder,
  23423. z: z,
  23424. group: group,
  23425. clippingContext: clippingContext
  23426. };
  23427. this.renderItems[ this.renderItemsIndex ] = renderItem;
  23428. } else {
  23429. renderItem.id = object.id;
  23430. renderItem.object = object;
  23431. renderItem.geometry = geometry;
  23432. renderItem.material = material;
  23433. renderItem.groupOrder = groupOrder;
  23434. renderItem.renderOrder = object.renderOrder;
  23435. renderItem.z = z;
  23436. renderItem.group = group;
  23437. renderItem.clippingContext = clippingContext;
  23438. }
  23439. this.renderItemsIndex ++;
  23440. return renderItem;
  23441. }
  23442. /**
  23443. * Pushes the given object as a render item to the internal render lists.
  23444. * The selected lists depend on the object properties.
  23445. *
  23446. * @param {Object3D} object - The 3D object.
  23447. * @param {BufferGeometry} geometry - The 3D object's geometry.
  23448. * @param {Material} material - The 3D object's material.
  23449. * @param {number} groupOrder - The current group order.
  23450. * @param {number} z - Th 3D object's depth value (z value in clip space).
  23451. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  23452. * @param {ClippingContext} clippingContext - The current clipping context.
  23453. */
  23454. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  23455. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  23456. if ( object.occlusionTest === true && this._lastOcclusionObject !== object ) {
  23457. this.occlusionQueryCount ++;
  23458. this._lastOcclusionObject = object;
  23459. }
  23460. if ( material.transparent === true || material.transmission > 0 ||
  23461. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  23462. ( material.backdropNode && material.backdropNode.isNode ) ) {
  23463. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  23464. this.transparent.push( renderItem );
  23465. } else {
  23466. this.opaque.push( renderItem );
  23467. }
  23468. }
  23469. /**
  23470. * Inserts the given object as a render item at the start of the internal render lists.
  23471. * The selected lists depend on the object properties.
  23472. *
  23473. * @param {Object3D} object - The 3D object.
  23474. * @param {BufferGeometry} geometry - The 3D object's geometry.
  23475. * @param {Material} material - The 3D object's material.
  23476. * @param {number} groupOrder - The current group order.
  23477. * @param {number} z - Th 3D object's depth value (z value in clip space).
  23478. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  23479. * @param {ClippingContext} clippingContext - The current clipping context.
  23480. */
  23481. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  23482. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  23483. if ( material.transparent === true || material.transmission > 0 ||
  23484. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  23485. ( material.backdropNode && material.backdropNode.isNode ) ) {
  23486. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  23487. this.transparent.unshift( renderItem );
  23488. } else {
  23489. this.opaque.unshift( renderItem );
  23490. }
  23491. }
  23492. /**
  23493. * Pushes render bundle group data into the render list.
  23494. *
  23495. * @param {Object} group - Bundle group data.
  23496. */
  23497. pushBundle( group ) {
  23498. this.bundles.push( group );
  23499. }
  23500. /**
  23501. * Pushes a light into the render list.
  23502. *
  23503. * @param {Light} light - The light.
  23504. */
  23505. pushLight( light ) {
  23506. this.lightsArray.push( light );
  23507. }
  23508. /**
  23509. * Sorts the internal render lists.
  23510. *
  23511. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  23512. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  23513. * @param {boolean} reversedDepth - Whether a reversed depth buffer is used or not.
  23514. */
  23515. sort( customOpaqueSort, customTransparentSort, reversedDepth ) {
  23516. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  23517. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  23518. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  23519. if ( reversedDepth ) {
  23520. this.opaque.reverse();
  23521. this.transparentDoublePass.reverse();
  23522. this.transparent.reverse();
  23523. }
  23524. }
  23525. /**
  23526. * This method performs finalizing tasks right after the render lists
  23527. * have been generated.
  23528. */
  23529. finish() {
  23530. // update lights
  23531. this.lightsNode.setLights( this.lighting.enabled ? this.lightsArray : _emptyArray );
  23532. // Clear references from inactive renderItems in the list
  23533. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  23534. const renderItem = this.renderItems[ i ];
  23535. if ( renderItem.id === null ) break;
  23536. renderItem.id = null;
  23537. renderItem.object = null;
  23538. renderItem.geometry = null;
  23539. renderItem.material = null;
  23540. renderItem.groupOrder = null;
  23541. renderItem.renderOrder = null;
  23542. renderItem.z = null;
  23543. renderItem.group = null;
  23544. renderItem.clippingContext = null;
  23545. }
  23546. this._lastOcclusionObject = null;
  23547. }
  23548. }
  23549. const _chainKeys$2 = [];
  23550. /**
  23551. * This renderer module manages the render lists which are unique
  23552. * per scene and camera combination.
  23553. *
  23554. * @private
  23555. */
  23556. class RenderLists {
  23557. /**
  23558. * Constructs a render lists management component.
  23559. *
  23560. * @param {Lighting} lighting - The lighting management component.
  23561. */
  23562. constructor( lighting ) {
  23563. /**
  23564. * The lighting management component.
  23565. *
  23566. * @type {Lighting}
  23567. */
  23568. this.lighting = lighting;
  23569. /**
  23570. * The internal chain map which holds the render lists.
  23571. *
  23572. * @type {ChainMap}
  23573. */
  23574. this.lists = new ChainMap();
  23575. }
  23576. /**
  23577. * Returns a render list for the given scene and camera.
  23578. *
  23579. * @param {Scene} scene - The scene.
  23580. * @param {Camera} camera - The camera.
  23581. * @return {RenderList} The render list.
  23582. */
  23583. get( scene, camera ) {
  23584. const lists = this.lists;
  23585. _chainKeys$2[ 0 ] = scene;
  23586. _chainKeys$2[ 1 ] = camera;
  23587. let list = lists.get( _chainKeys$2 );
  23588. if ( list === undefined ) {
  23589. list = new RenderList( this.lighting, scene, camera );
  23590. lists.set( _chainKeys$2, list );
  23591. }
  23592. _chainKeys$2[ 0 ] = null;
  23593. _chainKeys$2[ 1 ] = null;
  23594. return list;
  23595. }
  23596. /**
  23597. * Frees all internal resources.
  23598. */
  23599. dispose() {
  23600. this.lists = new ChainMap();
  23601. }
  23602. }
  23603. let _id$8 = 0;
  23604. /**
  23605. * Any render or compute command is executed in a specific context that defines
  23606. * the state of the renderer and its backend. Typical examples for such context
  23607. * data are the current clear values or data from the active framebuffer. This
  23608. * module is used to represent these contexts as objects.
  23609. *
  23610. * @private
  23611. */
  23612. class RenderContext {
  23613. /**
  23614. * Constructs a new render context.
  23615. */
  23616. constructor() {
  23617. /**
  23618. * The context's ID.
  23619. *
  23620. * @type {number}
  23621. */
  23622. this.id = _id$8 ++;
  23623. /**
  23624. * The MRT configuration.
  23625. *
  23626. * @type {?MRTNode}
  23627. * @default null
  23628. */
  23629. this.mrt = null;
  23630. /**
  23631. * Whether the current active framebuffer has a color attachment.
  23632. *
  23633. * @type {boolean}
  23634. * @default true
  23635. */
  23636. this.color = true;
  23637. /**
  23638. * Whether the color attachment should be cleared or not.
  23639. *
  23640. * @type {boolean}
  23641. * @default true
  23642. */
  23643. this.clearColor = true;
  23644. /**
  23645. * The clear color value.
  23646. *
  23647. * @type {Object}
  23648. * @default true
  23649. */
  23650. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  23651. /**
  23652. * Whether the current active framebuffer has a depth attachment.
  23653. *
  23654. * @type {boolean}
  23655. * @default true
  23656. */
  23657. this.depth = true;
  23658. /**
  23659. * Whether the depth attachment should be cleared or not.
  23660. *
  23661. * @type {boolean}
  23662. * @default true
  23663. */
  23664. this.clearDepth = true;
  23665. /**
  23666. * The clear depth value.
  23667. *
  23668. * @type {number}
  23669. * @default 1
  23670. */
  23671. this.clearDepthValue = 1;
  23672. /**
  23673. * Whether the current active framebuffer has a stencil attachment.
  23674. *
  23675. * @type {boolean}
  23676. * @default false
  23677. */
  23678. this.stencil = false;
  23679. /**
  23680. * Whether the stencil attachment should be cleared or not.
  23681. *
  23682. * @type {boolean}
  23683. * @default true
  23684. */
  23685. this.clearStencil = true;
  23686. /**
  23687. * The clear stencil value.
  23688. *
  23689. * @type {number}
  23690. * @default 1
  23691. */
  23692. this.clearStencilValue = 1;
  23693. /**
  23694. * By default the viewport encloses the entire framebuffer If a smaller
  23695. * viewport is manually defined, this property is to `true` by the renderer.
  23696. *
  23697. * @type {boolean}
  23698. * @default false
  23699. */
  23700. this.viewport = false;
  23701. /**
  23702. * The viewport value. This value is in physical pixels meaning it incorporates
  23703. * the renderer's pixel ratio. The viewport property of render targets or
  23704. * the renderer is in logical pixels.
  23705. *
  23706. * @type {Vector4}
  23707. */
  23708. this.viewportValue = new Vector4();
  23709. /**
  23710. * When the scissor test is active and scissor rectangle smaller than the
  23711. * framebuffers dimensions, this property is to `true` by the renderer.
  23712. *
  23713. * @type {boolean}
  23714. * @default false
  23715. */
  23716. this.scissor = false;
  23717. /**
  23718. * The scissor rectangle.
  23719. *
  23720. * @type {Vector4}
  23721. */
  23722. this.scissorValue = new Vector4();
  23723. /**
  23724. * The active render target.
  23725. *
  23726. * @type {?RenderTarget}
  23727. * @default null
  23728. */
  23729. this.renderTarget = null;
  23730. /**
  23731. * The textures of the active render target.
  23732. * `null` when no render target is set.
  23733. *
  23734. * @type {?Array<Texture>}
  23735. * @default null
  23736. */
  23737. this.textures = null;
  23738. /**
  23739. * The depth texture of the active render target.
  23740. * `null` when no render target is set.
  23741. *
  23742. * @type {?DepthTexture}
  23743. * @default null
  23744. */
  23745. this.depthTexture = null;
  23746. /**
  23747. * The active cube face.
  23748. *
  23749. * @type {number}
  23750. * @default 0
  23751. */
  23752. this.activeCubeFace = 0;
  23753. /**
  23754. * The active mipmap level.
  23755. *
  23756. * @type {number}
  23757. * @default 0
  23758. */
  23759. this.activeMipmapLevel = 0;
  23760. /**
  23761. * The number of MSAA samples. This value is always `1` when
  23762. * MSAA isn't used.
  23763. *
  23764. * @type {number}
  23765. * @default 1
  23766. */
  23767. this.sampleCount = 1;
  23768. /**
  23769. * The active render target's width in physical pixels.
  23770. *
  23771. * @type {number}
  23772. * @default 0
  23773. */
  23774. this.width = 0;
  23775. /**
  23776. * The active render target's height in physical pixels.
  23777. *
  23778. * @type {number}
  23779. * @default 0
  23780. */
  23781. this.height = 0;
  23782. /**
  23783. * The occlusion query count.
  23784. *
  23785. * @type {number}
  23786. * @default 0
  23787. */
  23788. this.occlusionQueryCount = 0;
  23789. /**
  23790. * The current clipping context.
  23791. *
  23792. * @type {?ClippingContext}
  23793. * @default null
  23794. */
  23795. this.clippingContext = null;
  23796. /**
  23797. * The current camera.
  23798. *
  23799. * @type {?Camera}
  23800. * @default null
  23801. */
  23802. this.camera = null;
  23803. /**
  23804. * This flag can be used for type testing.
  23805. *
  23806. * @type {boolean}
  23807. * @readonly
  23808. * @default true
  23809. */
  23810. this.isRenderContext = true;
  23811. }
  23812. /**
  23813. * Returns the cache key of this render context.
  23814. *
  23815. * @return {number} The cache key.
  23816. */
  23817. getCacheKey() {
  23818. return getCacheKey( this );
  23819. }
  23820. }
  23821. /**
  23822. * Computes a cache key for the given render context. This key
  23823. * should identify the render target state so it is possible to
  23824. * configure the correct attachments in the respective backend.
  23825. *
  23826. * @param {RenderContext} renderContext - The render context.
  23827. * @return {number} The cache key.
  23828. */
  23829. function getCacheKey( renderContext ) {
  23830. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  23831. const values = [ activeCubeFace, activeMipmapLevel ];
  23832. for ( const texture of textures ) {
  23833. values.push( texture.id );
  23834. }
  23835. return hashArray( values );
  23836. }
  23837. /**
  23838. * This module manages the render contexts of the renderer.
  23839. *
  23840. * @private
  23841. */
  23842. class RenderContexts {
  23843. /**
  23844. * Constructs a new render context management component.
  23845. *
  23846. * @param {Renderer} renderer - The renderer.
  23847. */
  23848. constructor( renderer ) {
  23849. /**
  23850. * The renderer.
  23851. *
  23852. * @type {Renderer}
  23853. */
  23854. this.renderer = renderer;
  23855. /**
  23856. * A dictionary that manages render contexts.
  23857. *
  23858. * @type {Object<string,RenderContext>}
  23859. */
  23860. this._renderContexts = {};
  23861. }
  23862. /**
  23863. * Returns a render context for the given scene, camera and render target.
  23864. *
  23865. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  23866. * @param {?MRTNode} [mrt=null] - The MRT configuration
  23867. * @param {?number} [callDepth=0] - The call depth of the renderer.
  23868. * @return {RenderContext} The render context.
  23869. */
  23870. get( renderTarget = null, mrt = null, callDepth = 0 ) {
  23871. //
  23872. let attachmentState;
  23873. if ( renderTarget === null ) {
  23874. attachmentState = 'default';
  23875. } else {
  23876. const format = renderTarget.texture.format;
  23877. const type = renderTarget.texture.type;
  23878. const count = renderTarget.textures.length;
  23879. attachmentState = `${ count }:${ format }:${ type }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  23880. }
  23881. //
  23882. const mrtState = ( mrt !== null ) ? mrt.id : 'default';
  23883. //
  23884. const renderStateKey = attachmentState + '-' + mrtState + '-' + callDepth;
  23885. let renderState = this._renderContexts[ renderStateKey ];
  23886. if ( renderState === undefined ) {
  23887. renderState = new RenderContext();
  23888. renderState.mrt = mrt;
  23889. this._renderContexts[ renderStateKey ] = renderState;
  23890. }
  23891. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  23892. renderState.clearDepthValue = this.renderer.getClearDepth();
  23893. renderState.clearStencilValue = this.renderer.getClearStencil();
  23894. return renderState;
  23895. }
  23896. /**
  23897. * Frees internal resources.
  23898. */
  23899. dispose() {
  23900. this._renderContexts = {};
  23901. }
  23902. }
  23903. const _size$3 = /*@__PURE__*/ new Vector3();
  23904. /**
  23905. * This module manages the textures of the renderer.
  23906. *
  23907. * @private
  23908. * @augments DataMap
  23909. */
  23910. class Textures extends DataMap {
  23911. /**
  23912. * Constructs a new texture management component.
  23913. *
  23914. * @param {Renderer} renderer - The renderer.
  23915. * @param {Backend} backend - The renderer's backend.
  23916. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  23917. */
  23918. constructor( renderer, backend, info ) {
  23919. super();
  23920. /**
  23921. * The renderer.
  23922. *
  23923. * @type {Renderer}
  23924. */
  23925. this.renderer = renderer;
  23926. /**
  23927. * The backend.
  23928. *
  23929. * @type {Backend}
  23930. */
  23931. this.backend = backend;
  23932. /**
  23933. * Renderer component for managing metrics and monitoring data.
  23934. *
  23935. * @type {Info}
  23936. */
  23937. this.info = info;
  23938. /**
  23939. * A set of HTMLTextures that need paint updates.
  23940. *
  23941. * @type {Set<HTMLTexture>}
  23942. */
  23943. this._htmlTextures = new Set();
  23944. }
  23945. /**
  23946. * Updates the given render target. Based on the given render target configuration,
  23947. * it updates the texture states representing the attachments of the framebuffer.
  23948. *
  23949. * @param {RenderTarget} renderTarget - The render target to update.
  23950. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  23951. */
  23952. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  23953. const renderTargetData = this.get( renderTarget );
  23954. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  23955. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  23956. const textures = renderTarget.textures;
  23957. const size = this.getSize( textures[ 0 ] );
  23958. const mipWidth = size.width >> activeMipmapLevel;
  23959. const mipHeight = size.height >> activeMipmapLevel;
  23960. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  23961. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  23962. let textureNeedsUpdate = false;
  23963. const hasArrayDepthTexture = depthTexture !== undefined && depthTexture.image !== undefined && depthTexture.image.depth > 1;
  23964. const useArrayDepth = size.depth > 1 && ( renderTarget.useArrayDepthTexture || renderTarget.multiview || hasArrayDepthTexture );
  23965. if ( depthTexture === undefined && useDepthTexture ) {
  23966. depthTexture = new DepthTexture();
  23967. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  23968. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  23969. depthTexture.image.width = mipWidth;
  23970. depthTexture.image.height = mipHeight;
  23971. depthTexture.image.depth = size.depth;
  23972. depthTexture.renderTarget = renderTarget;
  23973. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  23974. }
  23975. if ( depthTexture ) {
  23976. depthTexture.isArrayTexture = useArrayDepth;
  23977. }
  23978. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  23979. textureNeedsUpdate = true;
  23980. if ( depthTexture ) {
  23981. depthTexture.needsUpdate = true;
  23982. depthTexture.image.width = mipWidth;
  23983. depthTexture.image.height = mipHeight;
  23984. depthTexture.image.depth = useArrayDepth ? size.depth : 1;
  23985. }
  23986. }
  23987. renderTargetData.width = size.width;
  23988. renderTargetData.height = size.height;
  23989. renderTargetData.textures = textures;
  23990. renderTargetData.depthTexture = depthTexture || null;
  23991. renderTargetData.depth = renderTarget.depthBuffer;
  23992. renderTargetData.stencil = renderTarget.stencilBuffer;
  23993. renderTargetData.renderTarget = renderTarget;
  23994. if ( renderTargetData.sampleCount !== sampleCount ) {
  23995. textureNeedsUpdate = true;
  23996. if ( depthTexture ) {
  23997. depthTexture.needsUpdate = true;
  23998. }
  23999. renderTargetData.sampleCount = sampleCount;
  24000. }
  24001. //
  24002. const options = { sampleCount };
  24003. // XR render targets require no texture updates
  24004. if ( renderTarget.isXRRenderTarget !== true ) {
  24005. for ( let i = 0; i < textures.length; i ++ ) {
  24006. const texture = textures[ i ];
  24007. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  24008. this.updateTexture( texture, options );
  24009. }
  24010. if ( depthTexture ) {
  24011. this.updateTexture( depthTexture, options );
  24012. }
  24013. }
  24014. // dispose handler
  24015. if ( renderTargetData.initialized !== true ) {
  24016. renderTargetData.initialized = true;
  24017. this.info.memory.renderTargets ++;
  24018. // dispose
  24019. renderTargetData.onDispose = () => {
  24020. this._destroyRenderTarget( renderTarget );
  24021. };
  24022. renderTarget.addEventListener( 'dispose', renderTargetData.onDispose );
  24023. }
  24024. }
  24025. /**
  24026. * Updates the given texture. Depending on the texture state, this method
  24027. * triggers the upload of texture data to the GPU memory. If the texture data are
  24028. * not yet ready for the upload, it uses default texture data for as a placeholder.
  24029. *
  24030. * @param {Texture} texture - The texture to update.
  24031. * @param {Object} [options={}] - The options.
  24032. */
  24033. updateTexture( texture, options = {} ) {
  24034. const textureData = this.get( texture );
  24035. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  24036. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  24037. const backend = this.backend;
  24038. if ( isRenderTarget && textureData.initialized === true ) {
  24039. // it's an update
  24040. backend.destroyTexture( texture );
  24041. }
  24042. //
  24043. if ( texture.isFramebufferTexture ) {
  24044. const renderTarget = this.renderer.getRenderTarget();
  24045. if ( renderTarget ) {
  24046. texture.type = renderTarget.texture.type;
  24047. } else {
  24048. texture.type = UnsignedByteType;
  24049. }
  24050. }
  24051. // Ensure HTMLTexture elements are in the canvas before measuring size.
  24052. if ( texture.isHTMLTexture && texture.image ) {
  24053. const canvas = this.renderer.domElement;
  24054. if ( 'requestPaint' in canvas ) {
  24055. if ( ! canvas.hasAttribute( 'layoutsubtree' ) ) {
  24056. canvas.setAttribute( 'layoutsubtree', 'true' );
  24057. }
  24058. if ( texture.image.parentNode !== canvas ) {
  24059. canvas.appendChild( texture.image );
  24060. }
  24061. // Set up shared paint callback for all HTMLTextures.
  24062. if ( this._htmlTextures.size === 0 ) {
  24063. const htmlTextures = this._htmlTextures;
  24064. canvas.onpaint = ( event ) => {
  24065. const changed = event && event.changedElements;
  24066. for ( const t of htmlTextures ) {
  24067. if ( ! changed || changed.includes( t.image ) ) {
  24068. t.needsUpdate = true;
  24069. }
  24070. }
  24071. };
  24072. }
  24073. this._htmlTextures.add( texture );
  24074. }
  24075. }
  24076. //
  24077. const { width, height, depth } = this.getSize( texture );
  24078. options.width = width;
  24079. options.height = height;
  24080. options.depth = depth;
  24081. options.needsMipmaps = this.needsMipmaps( texture );
  24082. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  24083. // TODO: Uniformly handle mipmap definitions
  24084. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  24085. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  24086. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  24087. //
  24088. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  24089. backend.createTexture( texture, options );
  24090. textureData.generation = texture.version;
  24091. } else {
  24092. if ( texture.version > 0 ) {
  24093. const image = texture.image;
  24094. if ( image === undefined ) {
  24095. warn( 'Renderer: Texture marked for update but image is undefined.' );
  24096. } else if ( image.complete === false ) {
  24097. warn( 'Renderer: Texture marked for update but image is incomplete.' );
  24098. } else {
  24099. if ( texture.images ) {
  24100. const images = [];
  24101. for ( const image of texture.images ) {
  24102. images.push( image );
  24103. }
  24104. options.images = images;
  24105. } else {
  24106. options.image = image;
  24107. }
  24108. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  24109. backend.createTexture( texture, options );
  24110. textureData.isDefaultTexture = false;
  24111. textureData.generation = texture.version;
  24112. }
  24113. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  24114. const skipAutoGeneration = texture.isStorageTexture === true && texture.mipmapsAutoUpdate === false;
  24115. if ( options.needsMipmaps && texture.mipmaps.length === 0 && ! skipAutoGeneration ) {
  24116. backend.generateMipmaps( texture );
  24117. }
  24118. if ( texture.onUpdate ) texture.onUpdate( texture );
  24119. }
  24120. } else {
  24121. // async update
  24122. backend.createDefaultTexture( texture );
  24123. textureData.isDefaultTexture = true;
  24124. textureData.generation = texture.version;
  24125. }
  24126. }
  24127. // dispose handler
  24128. if ( textureData.initialized !== true ) {
  24129. textureData.initialized = true;
  24130. textureData.generation = texture.version;
  24131. textureData.bindGroups = new Set();
  24132. //
  24133. this.info.createTexture( texture );
  24134. //
  24135. if ( texture.isVideoTexture && ColorManagement.enabled === true && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  24136. warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  24137. }
  24138. // dispose
  24139. textureData.onDispose = () => {
  24140. this._destroyTexture( texture );
  24141. };
  24142. texture.addEventListener( 'dispose', textureData.onDispose );
  24143. }
  24144. //
  24145. textureData.version = texture.version;
  24146. }
  24147. /**
  24148. * Updates the sampler for the given texture. This method has no effect
  24149. * for the WebGL backend since it has no concept of samplers. Texture
  24150. * parameters are configured with the `texParameter()` command for each
  24151. * texture.
  24152. *
  24153. * In WebGPU, samplers are objects like textures and it's possible to share
  24154. * them when the texture parameters match.
  24155. *
  24156. * @param {Texture} texture - The texture to update the sampler for.
  24157. * @param {TextureNode} textureNode - The texture node to update the sampler with.
  24158. * @return {string} The current sampler key.
  24159. */
  24160. updateSampler( texture, textureNode ) {
  24161. return this.backend.updateSampler( texture, textureNode );
  24162. }
  24163. /**
  24164. * Computes the size of the given texture and writes the result
  24165. * into the target vector. This vector is also returned by the
  24166. * method.
  24167. *
  24168. * If no texture data are available for the compute yet, the method
  24169. * returns default size values.
  24170. *
  24171. * @param {Texture} texture - The texture to compute the size for.
  24172. * @param {Vector3} target - The target vector.
  24173. * @return {Vector3} The target vector.
  24174. */
  24175. getSize( texture, target = _size$3 ) {
  24176. let image = texture.images ? texture.images[ 0 ] : texture.image;
  24177. if ( image ) {
  24178. if ( image.image !== undefined ) image = image.image;
  24179. if ( texture.isHTMLTexture ) {
  24180. target.width = image.offsetWidth || 1;
  24181. target.height = image.offsetHeight || 1;
  24182. target.depth = 1;
  24183. } else if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  24184. target.width = image.videoWidth || 1;
  24185. target.height = image.videoHeight || 1;
  24186. target.depth = 1;
  24187. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( image instanceof VideoFrame ) ) {
  24188. target.width = image.displayWidth || 1;
  24189. target.height = image.displayHeight || 1;
  24190. target.depth = 1;
  24191. } else {
  24192. target.width = image.width || 1;
  24193. target.height = image.height || 1;
  24194. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  24195. }
  24196. } else {
  24197. target.width = target.height = target.depth = 1;
  24198. }
  24199. return target;
  24200. }
  24201. /**
  24202. * Computes the number of mipmap levels for the given texture.
  24203. *
  24204. * @param {Texture} texture - The texture.
  24205. * @param {number} width - The texture's width.
  24206. * @param {number} height - The texture's height.
  24207. * @return {number} The number of mipmap levels.
  24208. */
  24209. getMipLevels( texture, width, height ) {
  24210. let mipLevelCount;
  24211. if ( texture.mipmaps.length > 0 ) {
  24212. mipLevelCount = texture.mipmaps.length;
  24213. } else {
  24214. if ( texture.isCompressedTexture === true ) {
  24215. // it is not possible to compute mipmaps for compressed textures. So
  24216. // when no mipmaps are defined in "texture.mipmaps", force a texture
  24217. // level of 1
  24218. mipLevelCount = 1;
  24219. } else {
  24220. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  24221. }
  24222. }
  24223. return mipLevelCount;
  24224. }
  24225. /**
  24226. * Returns `true` if the given texture makes use of mipmapping.
  24227. *
  24228. * @param {Texture} texture - The texture.
  24229. * @return {boolean} Whether mipmaps are required or not.
  24230. */
  24231. needsMipmaps( texture ) {
  24232. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  24233. }
  24234. /**
  24235. * Frees internal resources when the given render target isn't
  24236. * required anymore.
  24237. *
  24238. * @param {RenderTarget} renderTarget - The render target to destroy.
  24239. */
  24240. _destroyRenderTarget( renderTarget ) {
  24241. if ( this.has( renderTarget ) === true ) {
  24242. const renderTargetData = this.get( renderTarget );
  24243. const textures = renderTargetData.textures;
  24244. const depthTexture = renderTargetData.depthTexture;
  24245. //
  24246. renderTarget.removeEventListener( 'dispose', renderTargetData.onDispose );
  24247. //
  24248. for ( let i = 0; i < textures.length; i ++ ) {
  24249. this._destroyTexture( textures[ i ] );
  24250. }
  24251. if ( depthTexture ) {
  24252. this._destroyTexture( depthTexture );
  24253. }
  24254. this.delete( renderTarget );
  24255. this.backend.delete( renderTarget );
  24256. this.info.memory.renderTargets --;
  24257. }
  24258. }
  24259. /**
  24260. * Frees internal resource when the given texture isn't
  24261. * required anymore.
  24262. *
  24263. * @param {Texture} texture - The texture to destroy.
  24264. */
  24265. _destroyTexture( texture ) {
  24266. if ( this.has( texture ) === true ) {
  24267. const textureData = this.get( texture );
  24268. //
  24269. texture.removeEventListener( 'dispose', textureData.onDispose );
  24270. // if a texture is not ready for use, it falls back to a default texture so it's possible
  24271. // to use it for rendering. If a texture in this state is disposed, it's important to
  24272. // not destroy/delete the underlying GPU texture object since it is cached and shared with
  24273. // other textures.
  24274. const isDefaultTexture = textureData.isDefaultTexture;
  24275. this.backend.destroyTexture( texture, isDefaultTexture );
  24276. // delete cached bind groups so they don't point to destroyed textures
  24277. if ( textureData.bindGroups ) {
  24278. for ( const bindGroup of textureData.bindGroups ) {
  24279. const bindingsData = this.backend.get( bindGroup );
  24280. bindingsData.groups = undefined;
  24281. bindingsData.versions = undefined;
  24282. // go through all bindings and if one points to the destroyed texture, trigger dispose as well
  24283. for ( const binding of bindGroup.bindings ) {
  24284. if ( binding.isSampler && binding.texture === texture ) {
  24285. binding.reset();
  24286. binding.release();
  24287. }
  24288. }
  24289. }
  24290. }
  24291. this._htmlTextures.delete( texture );
  24292. this.delete( texture );
  24293. this.info.destroyTexture( texture );
  24294. }
  24295. }
  24296. }
  24297. /**
  24298. * A four-component version of {@link Color} which is internally
  24299. * used by the renderer to represents clear color with alpha as
  24300. * one object.
  24301. *
  24302. * @private
  24303. * @augments Color
  24304. */
  24305. class Color4 extends Color {
  24306. /**
  24307. * Constructs a new four-component color.
  24308. * You can also pass a single THREE.Color, hex or
  24309. * string argument to this constructor.
  24310. *
  24311. * @param {number|string} [r=1] - The red value.
  24312. * @param {number} [g=1] - The green value.
  24313. * @param {number} [b=1] - The blue value.
  24314. * @param {number} [a=1] - The alpha value.
  24315. */
  24316. constructor( r, g, b, a = 1 ) {
  24317. super( r, g, b );
  24318. this.a = a;
  24319. }
  24320. /**
  24321. * Overwrites the default to honor alpha.
  24322. * You can also pass a single THREE.Color, hex or
  24323. * string argument to this method.
  24324. *
  24325. * @param {number|string|Color} r - The red value.
  24326. * @param {number} [g] - The green value.
  24327. * @param {number} [b] - The blue value.
  24328. * @param {number} [a=1] - The alpha value.
  24329. * @return {Color4} A reference to this object.
  24330. */
  24331. set( r, g, b, a = 1 ) {
  24332. this.a = a;
  24333. return super.set( r, g, b );
  24334. }
  24335. /**
  24336. * Overwrites the default to honor alpha.
  24337. *
  24338. * @param {Color4} color - The color to copy.
  24339. * @return {Color4} A reference to this object.
  24340. */
  24341. copy( color ) {
  24342. if ( color.a !== undefined ) this.a = color.a;
  24343. return super.copy( color );
  24344. }
  24345. /**
  24346. * Overwrites the default to honor alpha.
  24347. *
  24348. * @return {Color4} The cloned color.
  24349. */
  24350. clone() {
  24351. return new this.constructor( this.r, this.g, this.b, this.a );
  24352. }
  24353. }
  24354. /**
  24355. * A specialized context node designed to override specific target nodes within a
  24356. * node sub-graph or flow. This allows replacing specific inputs (e.g., normal
  24357. * and position vectors) dynamically during compilation for a specific flow node,
  24358. * without having to reconstruct or duplicate the source nodes.
  24359. *
  24360. * ```js
  24361. * // Method chaining example:
  24362. * node.overrideNode( positionLocal, () => positionLocal.add( vec3( 1, 0, 0 ) ) );
  24363. *
  24364. * // Context assignment example:
  24365. * material.contextNode = overrideNode( positionLocal, () => positionLocal.add( vec3( 1, 0, 0 ) ) );
  24366. * ```
  24367. *
  24368. * @augments ContextNode
  24369. */
  24370. class OverrideContextNode extends ContextNode {
  24371. /**
  24372. * Returns the type of the node.
  24373. *
  24374. * @type {string}
  24375. * @readonly
  24376. * @static
  24377. */
  24378. static get type() {
  24379. return 'OverrideContextNode';
  24380. }
  24381. /**
  24382. * Constructs a new override context node.
  24383. *
  24384. * @param {Map<Node, Function>} overrideNodes - A map mapping target nodes to their respective override callback functions.
  24385. * @param {Node|null} [flowNode=null] - The node whose context should be modified.
  24386. */
  24387. constructor( overrideNodes, flowNode = null ) {
  24388. super( flowNode, {
  24389. overrideNodes
  24390. } );
  24391. /**
  24392. * This flag can be used for type testing.
  24393. *
  24394. * @type {boolean}
  24395. * @readonly
  24396. * @default true
  24397. */
  24398. this.isOverrideContextNode = true;
  24399. }
  24400. /**
  24401. * Gathers the context data from all parent context nodes by traversing the hierarchy,
  24402. * merging the `overrideNodes` maps from all encountered `OverrideContextNode` instances.
  24403. *
  24404. * @return {Object} The gathered context data, containing the merged `overrideNodes` map.
  24405. */
  24406. getFlowContextData() {
  24407. const children = [];
  24408. this.traverse( ( node ) => {
  24409. if ( node.isOverrideContextNode === true ) {
  24410. children.push( node.value.overrideNodes );
  24411. }
  24412. } );
  24413. const overrideNodes = new Map( children.flatMap( ( map ) => Array.from( map.entries() ) ) );
  24414. const data = super.getFlowContextData();
  24415. data.overrideNodes = overrideNodes;
  24416. return data;
  24417. }
  24418. }
  24419. /**
  24420. * TSL function for creating an `OverrideContextNode` to override a single target node.
  24421. *
  24422. * ```js
  24423. * material.contextNode = overrideNode( positionLocal, ( builder ) => positionLocal.add( vec3( 1, 0, 0 ) ) );
  24424. * ```
  24425. *
  24426. * @tsl
  24427. * @function
  24428. * @param {Node} targetNode - The target node that should be overridden.
  24429. * @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.
  24430. * @param {Node|null} [flowNode=null] - The node whose context should be modified.
  24431. * @return {OverrideContextNode} The created override context node.
  24432. */
  24433. function overrideNode( targetNode, callback = null, flowNode = null ) {
  24434. if ( callback && callback.isNode ) {
  24435. const node = callback;
  24436. callback = () => node;
  24437. }
  24438. return new OverrideContextNode( new Map( [[ targetNode, callback ]] ), flowNode );
  24439. }
  24440. addMethodChaining( 'overrideNode', ( flowNode, node, callback ) => overrideNode( node, callback, flowNode ) );
  24441. /**
  24442. * TSL function for creating an `OverrideContextNode` to override multiple target nodes.
  24443. *
  24444. * ```js
  24445. * material.contextNode = overrideNodes( [
  24446. * [ positionView, customPositionView ],
  24447. * [ positionViewDirection, ( builder ) => customPositionViewDirection ]
  24448. * ] );
  24449. * ```
  24450. *
  24451. * @tsl
  24452. * @function
  24453. * @param {Map<Node, (Function|Node)>|Array<Array<Node|Function|Node>>} overrides - The overrides mapping target nodes to callback functions or overriding nodes.
  24454. * @param {Node|null} [flowNode=null] - The node whose context should be modified.
  24455. * @return {OverrideContextNode} The created override context node.
  24456. */
  24457. function overrideNodes( overrides, flowNode = null ) {
  24458. const overrideNodesMap = new Map();
  24459. for ( const [ node, value ] of overrides ) {
  24460. const callback = value !== null ? typeof value === 'function' ? value : () => value : null;
  24461. overrideNodesMap.set( node, callback );
  24462. }
  24463. return new OverrideContextNode( overrideNodesMap, flowNode );
  24464. }
  24465. addMethodChaining( 'overrideNodes', ( flowNode, overrides ) => overrideNodes( overrides, flowNode ) );
  24466. /**
  24467. * Special version of {@link PropertyNode} which is used for parameters.
  24468. *
  24469. * @augments PropertyNode
  24470. */
  24471. class ParameterNode extends PropertyNode {
  24472. static get type() {
  24473. return 'ParameterNode';
  24474. }
  24475. /**
  24476. * Constructs a new parameter node.
  24477. *
  24478. * @param {string} nodeType - The type of the node.
  24479. * @param {?string} [name=null] - The name of the parameter in the shader.
  24480. */
  24481. constructor( nodeType, name = null ) {
  24482. super( nodeType, name );
  24483. /**
  24484. * This flag can be used for type testing.
  24485. *
  24486. * @type {boolean}
  24487. * @readonly
  24488. * @default true
  24489. */
  24490. this.isParameterNode = true;
  24491. }
  24492. /**
  24493. * Gets the type of a member variable in the parameter node.
  24494. *
  24495. * @param {NodeBuilder} builder - The node builder.
  24496. * @param {string} name - The name of the member variable.
  24497. * @returns {string}
  24498. */
  24499. getMemberType( builder, name ) {
  24500. const type = this.getNodeType( builder );
  24501. const struct = builder.getStructTypeNode( type );
  24502. let memberType;
  24503. if ( struct !== null ) {
  24504. memberType = struct.getMemberType( builder, name );
  24505. } else {
  24506. error( `TSL: Member "${ name }" not found in struct "${ type }".`, new StackTrace() );
  24507. memberType = 'float';
  24508. }
  24509. return memberType;
  24510. }
  24511. getHash() {
  24512. return String( this.id );
  24513. }
  24514. generate() {
  24515. return this.name;
  24516. }
  24517. }
  24518. /**
  24519. * TSL function for creating a parameter node.
  24520. *
  24521. * @tsl
  24522. * @function
  24523. * @param {string} type - The type of the node.
  24524. * @param {?string} name - The name of the parameter in the shader.
  24525. * @returns {ParameterNode}
  24526. */
  24527. const parameter = ( type, name ) => new ParameterNode( type, name );
  24528. /**
  24529. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  24530. * They are usually needed in cases like `If`, `Else`.
  24531. *
  24532. * @augments Node
  24533. */
  24534. class StackNode extends Node {
  24535. static get type() {
  24536. return 'StackNode';
  24537. }
  24538. /**
  24539. * Constructs a new stack node.
  24540. *
  24541. * @param {?StackNode} [parent=null] - The parent stack node.
  24542. */
  24543. constructor( parent = null ) {
  24544. super();
  24545. /**
  24546. * List of nodes.
  24547. *
  24548. * @type {Array<Node>}
  24549. */
  24550. this.nodes = [];
  24551. /**
  24552. * The output node.
  24553. *
  24554. * @type {?Node}
  24555. * @default null
  24556. */
  24557. this.outputNode = null;
  24558. /**
  24559. * The parent stack node.
  24560. *
  24561. * @type {?StackNode}
  24562. * @default null
  24563. */
  24564. this.parent = parent;
  24565. /**
  24566. * The current conditional node.
  24567. *
  24568. * @private
  24569. * @type {ConditionalNode}
  24570. * @default null
  24571. */
  24572. this._currentCond = null;
  24573. /**
  24574. * The expression node. Only
  24575. * relevant for Switch/Case.
  24576. *
  24577. * @private
  24578. * @type {Node}
  24579. * @default null
  24580. */
  24581. this._expressionNode = null;
  24582. /**
  24583. * The current node being processed.
  24584. *
  24585. * @private
  24586. * @type {Node}
  24587. * @default null
  24588. */
  24589. this._currentNode = null;
  24590. /**
  24591. * Stores additional data for nodes that are added to the stack.
  24592. *
  24593. * @private
  24594. * @type {Map<Node, {delta: number}>}
  24595. */
  24596. this._nodeDataLibrary = new Map();
  24597. /**
  24598. * This flag can be used for type testing.
  24599. *
  24600. * @type {boolean}
  24601. * @readonly
  24602. * @default true
  24603. */
  24604. this.isStackNode = true;
  24605. }
  24606. getElementType( builder ) {
  24607. return this.outputNode ? this.outputNode.getElementType( builder ) : 'void';
  24608. }
  24609. generateNodeType( builder ) {
  24610. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  24611. }
  24612. getMemberType( builder, name ) {
  24613. return this.outputNode ? this.outputNode.getMemberType( builder, name ) : 'void';
  24614. }
  24615. /**
  24616. * Adds a node to this stack.
  24617. *
  24618. * @param {Node} node - The node to add.
  24619. * @param {number} [index=-1] - The index of the node. If not specified, the node will be added to the end of the stack.
  24620. * @return {StackNode} A reference to this stack node.
  24621. */
  24622. addToStack( node, index = -1 ) {
  24623. if ( node.isNode !== true ) {
  24624. error( 'TSL: Invalid node added to stack.', new StackTrace() );
  24625. return this;
  24626. }
  24627. if ( index === -1 ) {
  24628. if ( this._currentNode ) {
  24629. let nodeData = this._nodeDataLibrary.get( this._currentNode );
  24630. if ( nodeData === undefined ) {
  24631. nodeData = {
  24632. delta: 0
  24633. };
  24634. this._nodeDataLibrary.set( this._currentNode, nodeData );
  24635. }
  24636. nodeData.delta ++;
  24637. index = this.nodes.indexOf( this._currentNode ) + nodeData.delta;
  24638. } else {
  24639. index = this.nodes.length;
  24640. }
  24641. }
  24642. this.nodes.splice( index, 0, node );
  24643. return this;
  24644. }
  24645. /**
  24646. * Adds a node to the stack before the current node.
  24647. *
  24648. * @param {Node} node - The node to add.
  24649. * @return {StackNode} A reference to this stack node.
  24650. */
  24651. addToStackBefore( node ) {
  24652. const index = this._currentNode ? this.nodes.indexOf( this._currentNode ) : 0;
  24653. return this.addToStack( node, index );
  24654. }
  24655. /**
  24656. * Represent an `if` statement in TSL.
  24657. *
  24658. * @param {Node} boolNode - Represents the condition.
  24659. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  24660. * @return {StackNode} A reference to this stack node.
  24661. */
  24662. If( boolNode, method ) {
  24663. const methodNode = new ShaderNode( method );
  24664. this._currentCond = select( boolNode, methodNode );
  24665. return this.addToStack( this._currentCond );
  24666. }
  24667. /**
  24668. * Represent an `elseif` statement in TSL.
  24669. *
  24670. * @param {Node} boolNode - Represents the condition.
  24671. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  24672. * @return {StackNode} A reference to this stack node.
  24673. */
  24674. ElseIf( boolNode, method ) {
  24675. const methodNode = new ShaderNode( method );
  24676. const ifNode = select( boolNode, methodNode );
  24677. this._currentCond.elseNode = ifNode;
  24678. this._currentCond = ifNode;
  24679. return this;
  24680. }
  24681. /**
  24682. * Represent an `else` statement in TSL.
  24683. *
  24684. * @param {Function} method - TSL code which is executed in the `else` case.
  24685. * @return {StackNode} A reference to this stack node.
  24686. */
  24687. Else( method ) {
  24688. this._currentCond.elseNode = new ShaderNode( method );
  24689. return this;
  24690. }
  24691. /**
  24692. * Represents a `switch` statement in TSL.
  24693. *
  24694. * @param {any} expression - Represents the expression.
  24695. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  24696. * @return {StackNode} A reference to this stack node.
  24697. */
  24698. Switch( expression ) {
  24699. this._expressionNode = nodeObject( expression );
  24700. return this;
  24701. }
  24702. /**
  24703. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  24704. * The last parameter must be the callback method that should be executed in the `true` case.
  24705. *
  24706. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  24707. * @return {StackNode} A reference to this stack node.
  24708. */
  24709. Case( ...params ) {
  24710. const caseNodes = [];
  24711. // extract case nodes from the parameter list
  24712. if ( params.length >= 2 ) {
  24713. for ( let i = 0; i < params.length - 1; i ++ ) {
  24714. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  24715. }
  24716. } else {
  24717. error( 'TSL: Invalid parameter length. Case() requires at least two parameters.', new StackTrace() );
  24718. }
  24719. // extract method
  24720. const method = params[ params.length - 1 ];
  24721. const methodNode = new ShaderNode( method );
  24722. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  24723. let caseNode = caseNodes[ 0 ];
  24724. for ( let i = 1; i < caseNodes.length; i ++ ) {
  24725. caseNode = caseNode.or( caseNodes[ i ] );
  24726. }
  24727. // build condition
  24728. const condNode = select( caseNode, methodNode );
  24729. if ( this._currentCond === null ) {
  24730. this._currentCond = condNode;
  24731. return this.addToStack( this._currentCond );
  24732. } else {
  24733. this._currentCond.elseNode = condNode;
  24734. this._currentCond = condNode;
  24735. return this;
  24736. }
  24737. }
  24738. /**
  24739. * Represents the default code block of a Switch/Case statement.
  24740. *
  24741. * @param {Function} method - TSL code which is executed in the `else` case.
  24742. * @return {StackNode} A reference to this stack node.
  24743. */
  24744. Default( method ) {
  24745. this.Else( method );
  24746. return this;
  24747. }
  24748. setup( builder ) {
  24749. const nodeProperties = builder.getNodeProperties( this );
  24750. let index = 0;
  24751. for ( const childNode of this.getChildren() ) {
  24752. if ( childNode.isVarNode && childNode.isIntent( builder ) ) {
  24753. if ( childNode.isAssign( builder ) !== true ) {
  24754. continue;
  24755. }
  24756. }
  24757. nodeProperties[ 'node' + index ++ ] = childNode;
  24758. }
  24759. // return a outputNode if exists or null
  24760. return nodeProperties.outputNode || null;
  24761. }
  24762. build( builder, ...params ) {
  24763. const previousStack = getCurrentStack();
  24764. const buildStage = builder.buildStage;
  24765. setCurrentStack( this );
  24766. builder.setActiveStack( this );
  24767. //
  24768. for ( let i = 0; i < this.nodes.length; i ++ ) {
  24769. const node = this.nodes[ i ];
  24770. const previousNode = this._currentNode;
  24771. this._currentNode = node;
  24772. if ( node.isVarNode && node.isIntent( builder ) ) {
  24773. if ( node.isAssign( builder ) !== true ) {
  24774. continue;
  24775. }
  24776. }
  24777. if ( buildStage === 'setup' ) {
  24778. node.build( builder );
  24779. } else if ( buildStage === 'analyze' ) {
  24780. node.build( builder, this );
  24781. } else if ( buildStage === 'generate' ) {
  24782. const stages = builder.getDataFromNode( node, 'any' ).stages;
  24783. const parents = stages && stages[ builder.shaderStage ];
  24784. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  24785. continue; // skip var nodes that are only used in .toVarying()
  24786. }
  24787. node.build( builder, 'void' );
  24788. }
  24789. this._currentNode = previousNode;
  24790. }
  24791. //
  24792. let result;
  24793. if ( this.outputNode ) {
  24794. const buildResult = this.outputNode.build( builder, ...params );
  24795. if ( builder.buildStage !== 'generate' || this.outputNode.getNodeType( builder ) !== 'void' ) {
  24796. result = buildResult;
  24797. }
  24798. } else {
  24799. result = super.build( builder, ...params );
  24800. }
  24801. setCurrentStack( previousStack );
  24802. builder.removeActiveStack( this );
  24803. return result;
  24804. }
  24805. }
  24806. /**
  24807. * TSL function for creating a stack node.
  24808. *
  24809. * @tsl
  24810. * @function
  24811. * @param {?StackNode} [parent=null] - The parent stack node.
  24812. * @returns {StackNode}
  24813. */
  24814. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  24815. /**
  24816. * Generates a layout for struct members.
  24817. * This function takes an object representing struct members and returns an array of member layouts.
  24818. * Each member layout includes the member's name, type, and whether it is atomic.
  24819. *
  24820. * @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.
  24821. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  24822. */
  24823. function getMembersLayout( members ) {
  24824. return Object.entries( members ).map( ( [ name, value ] ) => {
  24825. if ( typeof value === 'string' ) {
  24826. return { name, type: value, atomic: false };
  24827. }
  24828. return { name, type: value.type, atomic: value.atomic || false };
  24829. } );
  24830. }
  24831. /**
  24832. * Represents a struct type node in the node-based system.
  24833. * This class is used to define and manage the layout and types of struct members.
  24834. * It extends the base Node class and provides methods to get the length of the struct,
  24835. * retrieve member types, and generate the struct type for a builder.
  24836. *
  24837. * @augments Node
  24838. */
  24839. class StructTypeNode extends Node {
  24840. static get type() {
  24841. return 'StructTypeNode';
  24842. }
  24843. /**
  24844. * Creates an instance of StructTypeNode.
  24845. *
  24846. * @param {Object} membersLayout - The layout of the members for the struct.
  24847. * @param {?string} [name=null] - The optional name of the struct.
  24848. */
  24849. constructor( membersLayout, name = null ) {
  24850. super( 'struct' );
  24851. /**
  24852. * The layout of the members for the struct
  24853. *
  24854. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  24855. */
  24856. this.membersLayout = getMembersLayout( membersLayout );
  24857. /**
  24858. * The name of the struct.
  24859. *
  24860. * @type {?string}
  24861. * @default null
  24862. */
  24863. this.name = name;
  24864. /**
  24865. * This flag can be used for type testing.
  24866. *
  24867. * @type {boolean}
  24868. * @readonly
  24869. * @default true
  24870. */
  24871. this.isStructTypeNode = true;
  24872. }
  24873. /**
  24874. * Returns the length of the struct in 4-byte elements (e.g. float or int components).
  24875. * The length is calculated by summing the lengths of the struct's members, accounting for memory alignment.
  24876. * To get the size in bytes, multiply the returned value by 4.
  24877. *
  24878. * @returns {number} The length of the struct in 4-byte elements.
  24879. */
  24880. getLength() {
  24881. let maxAlignment = 1; // maximum alignment value in this struct
  24882. let offset = 0; // global buffer offset in 4 byte elements
  24883. for ( const member of this.membersLayout ) {
  24884. const type = member.type;
  24885. const itemSize = getMemoryLengthFromType( type );
  24886. const alignment = getAlignmentFromType( type );
  24887. maxAlignment = Math.max( maxAlignment, alignment );
  24888. const chunkOffset = offset % maxAlignment; // offset in the current chunk of maxAlignment elements
  24889. const overhang = chunkOffset % alignment; // distance from the last aligned offset
  24890. if ( overhang !== 0 ) {
  24891. offset += alignment - overhang; // move to next aligned offset
  24892. }
  24893. offset += itemSize;
  24894. }
  24895. return ( Math.ceil( offset / maxAlignment ) * maxAlignment ); // ensure length is a multiple of maxAlignment
  24896. }
  24897. getMemberType( builder, name ) {
  24898. const member = this.membersLayout.find( m => m.name === name );
  24899. return member ? member.type : 'void';
  24900. }
  24901. generateNodeType( builder ) {
  24902. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  24903. return structType.name;
  24904. }
  24905. setup( builder ) {
  24906. builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  24907. builder.addInclude( this );
  24908. }
  24909. generate( builder ) {
  24910. return this.getNodeType( builder );
  24911. }
  24912. }
  24913. /**
  24914. * StructNode allows to create custom structures with multiple members.
  24915. * This can also be used to define structures in attribute and uniform data.
  24916. *
  24917. * ```js
  24918. * // Define a custom struct
  24919. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  24920. *
  24921. * // Create a new instance of the struct
  24922. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  24923. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  24924. *
  24925. * // Access the struct members
  24926. * const min = bb.get( 'min' );
  24927. *
  24928. * // Assign a new value to a member
  24929. * min.assign( vec3() );
  24930. * ```
  24931. * @augments Node
  24932. */
  24933. class StructNode extends Node {
  24934. static get type() {
  24935. return 'StructNode';
  24936. }
  24937. constructor( structTypeNode, values ) {
  24938. super( 'vec3' );
  24939. this.structTypeNode = structTypeNode;
  24940. this.values = values;
  24941. this.isStructNode = true;
  24942. }
  24943. generateNodeType( builder ) {
  24944. return this.structTypeNode.getNodeType( builder );
  24945. }
  24946. getMemberType( builder, name ) {
  24947. return this.structTypeNode.getMemberType( builder, name );
  24948. }
  24949. _getChildren() {
  24950. // Ensure struct type is the last child for correct code generation order
  24951. const children = super._getChildren();
  24952. const structTypeProperty = children.find( child => child.childNode === this.structTypeNode );
  24953. children.splice( children.indexOf( structTypeProperty ), 1 );
  24954. children.push( structTypeProperty );
  24955. return children;
  24956. }
  24957. generate( builder ) {
  24958. const nodeVar = builder.getVarFromNode( this );
  24959. const structType = nodeVar.type;
  24960. const propertyName = builder.getPropertyName( nodeVar );
  24961. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structTypeNode.membersLayout, this.values ) }`, this );
  24962. return nodeVar.name;
  24963. }
  24964. }
  24965. /**
  24966. * TSL function for creating a struct node.
  24967. *
  24968. * @tsl
  24969. * @function
  24970. * @param {Object} membersLayout - The layout of the struct members.
  24971. * @param {?string} [name=null] - The name of the struct.
  24972. * @returns {Function} The struct function.
  24973. */
  24974. const struct = ( membersLayout, name = null ) => {
  24975. const structType = new StructTypeNode( membersLayout, name );
  24976. const struct = ( ...params ) => {
  24977. let values = null;
  24978. if ( params.length > 0 ) {
  24979. if ( params[ 0 ].isNode ) {
  24980. values = {};
  24981. const names = Object.keys( membersLayout );
  24982. for ( let i = 0; i < params.length; i ++ ) {
  24983. values[ names[ i ] ] = params[ i ];
  24984. }
  24985. } else {
  24986. values = params[ 0 ];
  24987. }
  24988. }
  24989. return new StructNode( structType, values );
  24990. };
  24991. return nodeProxyConstructor( struct, structType );
  24992. };
  24993. /**
  24994. * This node can be used to define multiple outputs in a shader programs.
  24995. *
  24996. * @augments Node
  24997. */
  24998. class OutputStructNode extends Node {
  24999. static get type() {
  25000. return 'OutputStructNode';
  25001. }
  25002. /**
  25003. * Constructs a new output struct node. The constructor can be invoked with an
  25004. * arbitrary number of nodes representing the members.
  25005. *
  25006. * @param {...Node} members - A parameter list of nodes.
  25007. */
  25008. constructor( ...members ) {
  25009. super();
  25010. /**
  25011. * An array of nodes which defines the output.
  25012. *
  25013. * @type {Array<Node>}
  25014. */
  25015. this.members = members;
  25016. /**
  25017. * This flag can be used for type testing.
  25018. *
  25019. * @type {boolean}
  25020. * @readonly
  25021. * @default true
  25022. */
  25023. this.isOutputStructNode = true;
  25024. }
  25025. generateNodeType( /*builder*/ ) {
  25026. return 'OutputType';
  25027. }
  25028. generate( builder ) {
  25029. const nodeData = builder.getDataFromNode( this );
  25030. if ( nodeData.membersLayout === undefined ) {
  25031. const members = this.members;
  25032. const membersLayout = [];
  25033. for ( let i = 0; i < members.length; i ++ ) {
  25034. const name = 'm' + i;
  25035. const type = members[ i ].getNodeType( builder );
  25036. membersLayout.push( { name, type, index: i } );
  25037. }
  25038. nodeData.membersLayout = membersLayout;
  25039. nodeData.structType = builder.getOutputStructTypeFromNode( this, nodeData.membersLayout );
  25040. }
  25041. //
  25042. const propertyName = builder.getOutputStructName();
  25043. const members = this.members;
  25044. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  25045. for ( let i = 0; i < members.length; i ++ ) {
  25046. const snippet = members[ i ].build( builder, nodeData.membersLayout[ i ].type );
  25047. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  25048. }
  25049. return propertyName;
  25050. }
  25051. }
  25052. /**
  25053. * TSL function for creating an output struct node.
  25054. *
  25055. * @tsl
  25056. * @function
  25057. * @param {...Node} members - A parameter list of nodes.
  25058. * @returns {OutputStructNode}
  25059. */
  25060. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  25061. /**
  25062. * Represents blending configuration.
  25063. *
  25064. * This class encapsulates all blending-related properties that control how
  25065. * a material's colors are combined with the colors already in the frame buffer.
  25066. */
  25067. class BlendMode {
  25068. /**
  25069. * Constructs a new blending configuration.
  25070. *
  25071. * @param {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending|MaterialBlending)} [blending=NormalBlending] - The blending mode.
  25072. */
  25073. constructor( blending = NormalBlending ) {
  25074. /**
  25075. * Defines the blending type.
  25076. *
  25077. * It must be set to `CustomBlending` if custom blending properties like
  25078. * {@link BlendMode#blendSrc}, {@link BlendMode#blendDst} or {@link BlendMode#blendEquation}
  25079. * should have any effect.
  25080. *
  25081. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending|MaterialBlending)}
  25082. * @default NormalBlending
  25083. */
  25084. this.blending = blending;
  25085. /**
  25086. * Defines the blending source factor.
  25087. *
  25088. * This determines how the source (incoming) fragment color is factored before being added
  25089. * to the destination (existing) fragment color in the frame buffer.
  25090. *
  25091. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  25092. * @default SrcAlphaFactor
  25093. */
  25094. this.blendSrc = SrcAlphaFactor;
  25095. /**
  25096. * Defines the blending destination factor.
  25097. *
  25098. * This determines how the destination (existing) fragment color in the frame buffer
  25099. * is factored before being combined with the source (incoming) fragment color.
  25100. *
  25101. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  25102. * @default OneMinusSrcAlphaFactor
  25103. */
  25104. this.blendDst = OneMinusSrcAlphaFactor;
  25105. /**
  25106. * Defines the blending equation.
  25107. *
  25108. * This determines how the source and destination colors are combined.
  25109. *
  25110. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  25111. * @default AddEquation
  25112. */
  25113. this.blendEquation = AddEquation;
  25114. /**
  25115. * Defines the blending source alpha factor.
  25116. *
  25117. * When set, this allows separate control of the alpha channel's source blending factor.
  25118. * If `null`, {@link BlendMode#blendSrc} is used for the alpha channel as well.
  25119. *
  25120. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  25121. * @default null
  25122. */
  25123. this.blendSrcAlpha = null;
  25124. /**
  25125. * Defines the blending destination alpha factor.
  25126. *
  25127. * When set, this allows separate control of the alpha channel's destination blending factor.
  25128. * If `null`, {@link BlendMode#blendDst} is used for the alpha channel as well.
  25129. *
  25130. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  25131. * @default null
  25132. */
  25133. this.blendDstAlpha = null;
  25134. /**
  25135. * Defines the blending equation of the alpha channel.
  25136. *
  25137. * When set, this allows separate control of the alpha channel's blending equation.
  25138. * If `null`, {@link BlendMode#blendEquation} is used for the alpha channel as well.
  25139. *
  25140. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  25141. * @default null
  25142. */
  25143. this.blendEquationAlpha = null;
  25144. /**
  25145. * Defines whether to premultiply the alpha (transparency) value.
  25146. *
  25147. * If `true`, the RGB color of the texture or material is multiplied by its alpha value.
  25148. * This is useful for transparent textures/materials where the color data
  25149. * should already include the transparency information.
  25150. *
  25151. * @type {boolean}
  25152. * @default false
  25153. */
  25154. this.premultiplyAlpha = false;
  25155. }
  25156. /**
  25157. * Copies the blending properties from the given source to this instance.
  25158. *
  25159. * @param {BlendMode} source - The blending configuration to copy from.
  25160. * @return {BlendMode} A reference to this instance.
  25161. */
  25162. copy( source ) {
  25163. this.blending = source.blending;
  25164. this.blendSrc = source.blendSrc;
  25165. this.blendDst = source.blendDst;
  25166. this.blendEquation = source.blendEquation;
  25167. this.blendSrcAlpha = source.blendSrcAlpha;
  25168. this.blendDstAlpha = source.blendDstAlpha;
  25169. this.blendEquationAlpha = source.blendEquationAlpha;
  25170. this.premultiplyAlpha = source.premultiplyAlpha;
  25171. return this;
  25172. }
  25173. /**
  25174. * Returns a clone of this blending configuration.
  25175. *
  25176. * @return {BlendMode} A new Blending instance with the same properties.
  25177. */
  25178. clone() {
  25179. return new this.constructor().copy( this );
  25180. }
  25181. }
  25182. // Predefined blend modes for MRT nodes.
  25183. const _noBlending = /**@__PURE__*/ new BlendMode( NoBlending );
  25184. const _materialBlending = /**@__PURE__*/ new BlendMode( MaterialBlending );
  25185. /**
  25186. * Returns the MRT texture index for the given name.
  25187. *
  25188. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  25189. * @param {string} name - The name of the MRT texture which index is requested.
  25190. * @return {number} The texture index.
  25191. */
  25192. function getTextureIndex( textures, name ) {
  25193. for ( let i = 0; i < textures.length; i ++ ) {
  25194. if ( textures[ i ].name === name ) {
  25195. return i;
  25196. }
  25197. }
  25198. return -1;
  25199. }
  25200. /**
  25201. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  25202. * post-processing is shown below:
  25203. * ```js
  25204. * const mrtNode = mrt( {
  25205. * output: output,
  25206. * normal: normalView
  25207. * } ) ;
  25208. * ```
  25209. * The MRT output is defined as a dictionary.
  25210. *
  25211. * @augments OutputStructNode
  25212. */
  25213. class MRTNode extends OutputStructNode {
  25214. static get type() {
  25215. return 'MRTNode';
  25216. }
  25217. /**
  25218. * Constructs a new output struct node.
  25219. *
  25220. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  25221. */
  25222. constructor( outputNodes ) {
  25223. super();
  25224. /**
  25225. * A dictionary representing the MRT outputs. The key
  25226. * is the name of the output, the value the node which produces
  25227. * the output result.
  25228. *
  25229. * @type {Object<string, Node>}
  25230. */
  25231. this.outputNodes = outputNodes;
  25232. /**
  25233. * A dictionary storing the blend modes for each output.
  25234. *
  25235. * @type {Object<string, BlendMode>}
  25236. */
  25237. this.blendModes = {
  25238. output: _materialBlending
  25239. };
  25240. /**
  25241. * This flag can be used for type testing.
  25242. *
  25243. * @type {boolean}
  25244. * @readonly
  25245. * @default true
  25246. */
  25247. this.isMRTNode = true;
  25248. }
  25249. /**
  25250. * Sets the blend mode for the given output name.
  25251. *
  25252. * @param {string} name - The name of the output.
  25253. * @param {BlendMode} blend - The blending mode.
  25254. * @return {MRTNode} The current MRT node.
  25255. */
  25256. setBlendMode( name, blend ) {
  25257. this.blendModes[ name ] = blend;
  25258. return this;
  25259. }
  25260. /**
  25261. * Returns the blend mode for the given output name.
  25262. *
  25263. * @param {string} name - The name of the output.
  25264. * @return {BlendMode} The blend mode.
  25265. */
  25266. getBlendMode( name ) {
  25267. return this.blendModes[ name ] || _noBlending;
  25268. }
  25269. /**
  25270. * Returns `true` if the MRT node has an output with the given name.
  25271. *
  25272. * @param {string} name - The name of the output.
  25273. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  25274. */
  25275. has( name ) {
  25276. return this.outputNodes[ name ] !== undefined;
  25277. }
  25278. /**
  25279. * Returns the output node for the given name.
  25280. *
  25281. * @param {string} name - The name of the output.
  25282. * @return {Node} The output node.
  25283. */
  25284. get( name ) {
  25285. return this.outputNodes[ name ];
  25286. }
  25287. /**
  25288. * Merges the outputs of the given MRT node with the outputs of this node.
  25289. *
  25290. * @param {MRTNode} mrtNode - The MRT to merge.
  25291. * @return {MRTNode} A new MRT node with merged outputs..
  25292. */
  25293. merge( mrtNode ) {
  25294. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  25295. const blendings = { ...this.blendModes, ...mrtNode.blendModes };
  25296. const mrtTarget = mrt( outputs );
  25297. mrtTarget.blendings = blendings;
  25298. return mrtTarget;
  25299. }
  25300. setup( builder ) {
  25301. const outputNodes = this.outputNodes;
  25302. const mrt = builder.renderer.getRenderTarget();
  25303. const members = [];
  25304. const textures = mrt.textures;
  25305. for ( const name in outputNodes ) {
  25306. const index = getTextureIndex( textures, name );
  25307. const type = builder.getOutputType( index );
  25308. members[ index ] = outputNodes[ name ].convert( type );
  25309. }
  25310. this.members = members;
  25311. return super.setup( builder );
  25312. }
  25313. }
  25314. /**
  25315. * TSL function for creating a MRT node.
  25316. *
  25317. * @tsl
  25318. * @function
  25319. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  25320. * @returns {MRTNode}
  25321. */
  25322. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  25323. /**
  25324. * This node represents an operation that reinterprets the bit representation of a value
  25325. * in one type as a value in another type.
  25326. *
  25327. * @augments TempNode
  25328. */
  25329. class BitcastNode extends TempNode {
  25330. static get type() {
  25331. return 'BitcastNode';
  25332. }
  25333. /**
  25334. * Constructs a new bitcast node.
  25335. *
  25336. * @param {Node} valueNode - The value to convert.
  25337. * @param {string} conversionType - The type to convert to.
  25338. * @param {?string} [inputType = null] - The expected input data type of the bitcast operation.
  25339. */
  25340. constructor( valueNode, conversionType, inputType = null ) {
  25341. super();
  25342. /**
  25343. * The data to bitcast to a new type.
  25344. *
  25345. * @type {Node}
  25346. */
  25347. this.valueNode = valueNode;
  25348. /**
  25349. * The type the value will be converted to.
  25350. *
  25351. * @type {string}
  25352. */
  25353. this.conversionType = conversionType;
  25354. /**
  25355. * The expected input data type of the bitcast operation.
  25356. *
  25357. *
  25358. * @type {string}
  25359. * @default null
  25360. */
  25361. this.inputType = inputType;
  25362. /**
  25363. * This flag can be used for type testing.
  25364. *
  25365. * @type {boolean}
  25366. * @readonly
  25367. * @default true
  25368. */
  25369. this.isBitcastNode = true;
  25370. }
  25371. generateNodeType( builder ) {
  25372. // GLSL aliasing
  25373. if ( this.inputType !== null ) {
  25374. const valueType = this.valueNode.getNodeType( builder );
  25375. const valueLength = builder.getTypeLength( valueType );
  25376. return builder.getTypeFromLength( valueLength, this.conversionType );
  25377. }
  25378. return this.conversionType;
  25379. }
  25380. generate( builder ) {
  25381. const type = this.getNodeType( builder );
  25382. let inputType = '';
  25383. if ( this.inputType !== null ) {
  25384. const valueType = this.valueNode.getNodeType( builder );
  25385. const valueTypeLength = builder.getTypeLength( valueType );
  25386. inputType = valueTypeLength === 1 ? this.inputType : builder.changeComponentType( valueType, this.inputType );
  25387. } else {
  25388. inputType = this.valueNode.getNodeType( builder );
  25389. }
  25390. return `${ builder.getBitcastMethod( type, inputType ) }( ${ this.valueNode.build( builder, inputType ) } )`;
  25391. }
  25392. }
  25393. /**
  25394. * Reinterpret the bit representation of a value in one type as a value in another type.
  25395. *
  25396. * @tsl
  25397. * @function
  25398. * @param {Node | number} x - The parameter.
  25399. * @param {string} y - The new type.
  25400. * @returns {Node}
  25401. */
  25402. const bitcast = /*@__PURE__*/ nodeProxyIntent( BitcastNode ).setParameterLength( 2 );
  25403. /**
  25404. * Bitcasts a float or a vector of floats to a corresponding integer type with the same element size.
  25405. *
  25406. * @tsl
  25407. * @function
  25408. * @param {Node<float>} value - The float or vector of floats to bitcast.
  25409. * @returns {BitcastNode}
  25410. */
  25411. const floatBitsToInt = ( value ) => new BitcastNode( value, 'int', 'float' );
  25412. /**
  25413. * Bitcasts a float or a vector of floats to a corresponding unsigned integer type with the same element size.
  25414. *
  25415. * @tsl
  25416. * @function
  25417. * @param {Node<float>} value - The float or vector of floats to bitcast.
  25418. * @returns {BitcastNode}
  25419. */
  25420. const floatBitsToUint = ( value ) => new BitcastNode( value, 'uint', 'float' );
  25421. /**
  25422. * Bitcasts an integer or a vector of integers to a corresponding float type with the same element size.
  25423. *
  25424. * @tsl
  25425. * @function
  25426. * @param {Node<int>} value - The integer or vector of integers to bitcast.
  25427. * @returns {BitcastNode}
  25428. */
  25429. const intBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'int' );
  25430. /**
  25431. * Bitcast an unsigned integer or a vector of unsigned integers to a corresponding float type with the same element size.
  25432. *
  25433. * @tsl
  25434. * @function
  25435. * @param {Node<uint>} value - The unsigned integer or vector of unsigned integers to bitcast.
  25436. * @returns {BitcastNode}
  25437. */
  25438. const uintBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'uint' );
  25439. const registeredBitcountFunctions = {};
  25440. /**
  25441. * This node represents an operation that counts the bits of a piece of shader data.
  25442. *
  25443. * @augments MathNode
  25444. */
  25445. class BitcountNode extends MathNode {
  25446. static get type() {
  25447. return 'BitcountNode';
  25448. }
  25449. /**
  25450. * Constructs a new math node.
  25451. *
  25452. * @param {'countTrailingZeros'|'countLeadingZeros'|'countOneBits'} method - The method name.
  25453. * @param {Node} aNode - The first input.
  25454. */
  25455. constructor( method, aNode ) {
  25456. super( method, aNode );
  25457. /**
  25458. * This flag can be used for type testing.
  25459. *
  25460. * @type {boolean}
  25461. * @readonly
  25462. * @default true
  25463. */
  25464. this.isBitcountNode = true;
  25465. }
  25466. /**
  25467. * Casts the input value of the function to an integer if necessary.
  25468. *
  25469. * @private
  25470. * @param {Node<uint>|Node<int>} inputNode - The input value.
  25471. * @param {Node<uint>} outputNode - The output value.
  25472. * @param {string} elementType - The type of the input value.
  25473. */
  25474. _resolveElementType( inputNode, outputNode, elementType ) {
  25475. if ( elementType === 'int' ) {
  25476. outputNode.assign( bitcast( inputNode, 'uint' ) );
  25477. } else {
  25478. outputNode.assign( inputNode );
  25479. }
  25480. }
  25481. _returnDataNode( inputType ) {
  25482. switch ( inputType ) {
  25483. case 'uint': {
  25484. return uint;
  25485. }
  25486. case 'int': {
  25487. return int;
  25488. }
  25489. case 'uvec2': {
  25490. return uvec2;
  25491. }
  25492. case 'uvec3': {
  25493. return uvec3;
  25494. }
  25495. case 'uvec4': {
  25496. return uvec4;
  25497. }
  25498. case 'ivec2': {
  25499. return ivec2;
  25500. }
  25501. case 'ivec3': {
  25502. return ivec3;
  25503. }
  25504. case 'ivec4': {
  25505. return ivec4;
  25506. }
  25507. }
  25508. }
  25509. /**
  25510. * Creates and registers a reusable GLSL function that emulates the behavior of countTrailingZeros.
  25511. *
  25512. * @private
  25513. * @param {string} method - The name of the function to create.
  25514. * @param {string} elementType - The type of the input value.
  25515. * @returns {Function} - The generated function
  25516. */
  25517. _createTrailingZerosBaseLayout( method, elementType ) {
  25518. const outputConvertNode = this._returnDataNode( elementType );
  25519. const fnDef = Fn( ( [ value ] ) => {
  25520. const v = uint( 0.0 );
  25521. this._resolveElementType( value, v, elementType );
  25522. const f = float( v.bitAnd( negate( v ) ) );
  25523. const uintBits = floatBitsToUint( f );
  25524. const numTrailingZeros = ( uintBits.shiftRight( 23 ) ).sub( 127 );
  25525. return outputConvertNode( numTrailingZeros );
  25526. } ).setLayout( {
  25527. name: method,
  25528. type: elementType,
  25529. inputs: [
  25530. { name: 'value', type: elementType }
  25531. ]
  25532. } );
  25533. return fnDef;
  25534. }
  25535. /**
  25536. * Creates and registers a reusable GLSL function that emulates the behavior of countLeadingZeros.
  25537. *
  25538. * @private
  25539. * @param {string} method - The name of the function to create.
  25540. * @param {string} elementType - The type of the input value.
  25541. * @returns {Function} - The generated function
  25542. */
  25543. _createLeadingZerosBaseLayout( method, elementType ) {
  25544. const outputConvertNode = this._returnDataNode( elementType );
  25545. const fnDef = Fn( ( [ value ] ) => {
  25546. If( value.equal( uint( 0 ) ), () => {
  25547. return uint( 32 );
  25548. } );
  25549. const v = uint( 0 );
  25550. const n = uint( 0 );
  25551. this._resolveElementType( value, v, elementType );
  25552. If( v.shiftRight( 16 ).equal( 0 ), () => {
  25553. n.addAssign( 16 );
  25554. v.shiftLeftAssign( 16 );
  25555. } );
  25556. If( v.shiftRight( 24 ).equal( 0 ), () => {
  25557. n.addAssign( 8 );
  25558. v.shiftLeftAssign( 8 );
  25559. } );
  25560. If( v.shiftRight( 28 ).equal( 0 ), () => {
  25561. n.addAssign( 4 );
  25562. v.shiftLeftAssign( 4 );
  25563. } );
  25564. If( v.shiftRight( 30 ).equal( 0 ), () => {
  25565. n.addAssign( 2 );
  25566. v.shiftLeftAssign( 2 );
  25567. } );
  25568. If( v.shiftRight( 31 ).equal( 0 ), () => {
  25569. n.addAssign( 1 );
  25570. } );
  25571. return outputConvertNode( n );
  25572. } ).setLayout( {
  25573. name: method,
  25574. type: elementType,
  25575. inputs: [
  25576. { name: 'value', type: elementType }
  25577. ]
  25578. } );
  25579. return fnDef;
  25580. }
  25581. /**
  25582. * Creates and registers a reusable GLSL function that emulates the behavior of countOneBits.
  25583. *
  25584. * @private
  25585. * @param {string} method - The name of the function to create.
  25586. * @param {string} elementType - The type of the input value.
  25587. * @returns {Function} - The generated function
  25588. */
  25589. _createOneBitsBaseLayout( method, elementType ) {
  25590. const outputConvertNode = this._returnDataNode( elementType );
  25591. const fnDef = Fn( ( [ value ] ) => {
  25592. const v = uint( 0.0 );
  25593. this._resolveElementType( value, v, elementType );
  25594. v.assign( v.sub( v.shiftRight( uint( 1 ) ).bitAnd( uint( 0x55555555 ) ) ) );
  25595. v.assign( v.bitAnd( uint( 0x33333333 ) ).add( v.shiftRight( uint( 2 ) ).bitAnd( uint( 0x33333333 ) ) ) );
  25596. const numBits = v.add( v.shiftRight( uint( 4 ) ) ).bitAnd( uint( 0xF0F0F0F ) ).mul( uint( 0x1010101 ) ).shiftRight( uint( 24 ) );
  25597. return outputConvertNode( numBits );
  25598. } ).setLayout( {
  25599. name: method,
  25600. type: elementType,
  25601. inputs: [
  25602. { name: 'value', type: elementType }
  25603. ]
  25604. } );
  25605. return fnDef;
  25606. }
  25607. /**
  25608. * Creates and registers a reusable GLSL function that emulates the behavior of the specified bitcount function.
  25609. * including considerations for component-wise bitcounts on vector type inputs.
  25610. *
  25611. * @private
  25612. * @param {string} method - The name of the function to create.
  25613. * @param {string} inputType - The type of the input value.
  25614. * @param {number} typeLength - The vec length of the input value.
  25615. * @param {Function} baseFn - The base function that operates on an individual component of the vector.
  25616. * @returns {Function} - The alias function for the specified bitcount method.
  25617. */
  25618. _createMainLayout( method, inputType, typeLength, baseFn ) {
  25619. const outputConvertNode = this._returnDataNode( inputType );
  25620. const fnDef = Fn( ( [ value ] ) => {
  25621. if ( typeLength === 1 ) {
  25622. return outputConvertNode( baseFn( value ) );
  25623. } else {
  25624. const vec = outputConvertNode( 0 );
  25625. const components = [ 'x', 'y', 'z', 'w' ];
  25626. for ( let i = 0; i < typeLength; i ++ ) {
  25627. const component = components[ i ];
  25628. vec[ component ].assign( baseFn( value[ component ] ) );
  25629. }
  25630. return vec;
  25631. }
  25632. } ).setLayout( {
  25633. name: method,
  25634. type: inputType,
  25635. inputs: [
  25636. { name: 'value', type: inputType }
  25637. ]
  25638. } );
  25639. return fnDef;
  25640. }
  25641. setup( builder ) {
  25642. const { method, aNode } = this;
  25643. const { renderer } = builder;
  25644. if ( renderer.backend.isWebGPUBackend ) {
  25645. // use built-in WGSL functions for WebGPU
  25646. return super.setup( builder );
  25647. }
  25648. const inputType = this.getInputType( builder );
  25649. const elementType = builder.getElementType( inputType );
  25650. const typeLength = builder.getTypeLength( inputType );
  25651. const baseMethod = `${method}_base_${elementType}`;
  25652. const newMethod = `${method}_${inputType}`;
  25653. let baseFn = registeredBitcountFunctions[ baseMethod ];
  25654. if ( baseFn === undefined ) {
  25655. switch ( method ) {
  25656. case BitcountNode.COUNT_LEADING_ZEROS: {
  25657. baseFn = this._createLeadingZerosBaseLayout( baseMethod, elementType );
  25658. break;
  25659. }
  25660. case BitcountNode.COUNT_TRAILING_ZEROS: {
  25661. baseFn = this._createTrailingZerosBaseLayout( baseMethod, elementType );
  25662. break;
  25663. }
  25664. case BitcountNode.COUNT_ONE_BITS: {
  25665. baseFn = this._createOneBitsBaseLayout( baseMethod, elementType );
  25666. break;
  25667. }
  25668. }
  25669. registeredBitcountFunctions[ baseMethod ] = baseFn;
  25670. }
  25671. let fn = registeredBitcountFunctions[ newMethod ];
  25672. if ( fn === undefined ) {
  25673. fn = this._createMainLayout( newMethod, inputType, typeLength, baseFn );
  25674. registeredBitcountFunctions[ newMethod ] = fn;
  25675. }
  25676. const output = Fn( () => {
  25677. return fn(
  25678. aNode,
  25679. );
  25680. } );
  25681. return output();
  25682. }
  25683. }
  25684. BitcountNode.COUNT_TRAILING_ZEROS = 'countTrailingZeros';
  25685. BitcountNode.COUNT_LEADING_ZEROS = 'countLeadingZeros';
  25686. BitcountNode.COUNT_ONE_BITS = 'countOneBits';
  25687. /**
  25688. * Finds the number of consecutive 0 bits from the least significant bit of the input value,
  25689. * which is also the index of the least significant bit of the input value.
  25690. *
  25691. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  25692. *
  25693. * @tsl
  25694. * @function
  25695. * @param {Node | number} x - The input value.
  25696. * @returns {Node}
  25697. */
  25698. const countTrailingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_TRAILING_ZEROS ).setParameterLength( 1 );
  25699. /**
  25700. * Finds the number of consecutive 0 bits starting from the most significant bit of the input value.
  25701. *
  25702. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  25703. *
  25704. * @tsl
  25705. * @function
  25706. * @param {Node | number} x - The input value.
  25707. * @returns {Node}
  25708. */
  25709. const countLeadingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_LEADING_ZEROS ).setParameterLength( 1 );
  25710. /**
  25711. * Finds the number of '1' bits set in the input value
  25712. *
  25713. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  25714. *
  25715. * @tsl
  25716. * @function
  25717. * @returns {Node}
  25718. */
  25719. const countOneBits = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_ONE_BITS ).setParameterLength( 1 );
  25720. /**
  25721. * Generates a hash value in the range `[0, 1]` from the given seed.
  25722. *
  25723. * @tsl
  25724. * @function
  25725. * @param {Node<float>} seed - The seed.
  25726. * @return {Node<float>} The hash value.
  25727. */
  25728. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  25729. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  25730. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  25731. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  25732. const result = word.shiftRight( 22 ).bitXor( word );
  25733. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  25734. } );
  25735. /**
  25736. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  25737. * The corners are mapped to `0` and the center to `1`.
  25738. * Reference: {@link https://iquilezles.org/articles/functions/}.
  25739. *
  25740. * @tsl
  25741. * @function
  25742. * @param {Node<float>} x - The value to remap.
  25743. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  25744. * @return {Node<float>} The remapped value.
  25745. */
  25746. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  25747. /**
  25748. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  25749. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  25750. * Reference: {@link https://iquilezles.org/articles/functions/}.
  25751. *
  25752. * @tsl
  25753. * @function
  25754. * @param {Node<float>} x - The value to remap.
  25755. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  25756. * @return {Node<float>} The remapped value.
  25757. */
  25758. 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 ) );
  25759. /**
  25760. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  25761. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  25762. * Reference: {@link https://iquilezles.org/articles/functions/}.
  25763. *
  25764. * @tsl
  25765. * @function
  25766. * @param {Node<float>} x - The value to remap.
  25767. * @param {Node<float>} a - First control parameter.
  25768. * @param {Node<float>} b - Second control parameter.
  25769. * @return {Node<float>} The remapped value.
  25770. */
  25771. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  25772. /**
  25773. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  25774. * Reference: {@link https://iquilezles.org/articles/functions/}.
  25775. *
  25776. * @tsl
  25777. * @function
  25778. * @param {Node<float>} x - The value to compute the sin for.
  25779. * @param {Node<float>} k - Controls the amount of bounces.
  25780. * @return {Node<float>} The result value.
  25781. */
  25782. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  25783. /**
  25784. * This node represents an operation that packs floating-point values of a vector into an unsigned 32-bit integer
  25785. *
  25786. * @augments TempNode
  25787. */
  25788. class PackFloatNode extends TempNode {
  25789. static get type() {
  25790. return 'PackFloatNode';
  25791. }
  25792. /**
  25793. *
  25794. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  25795. * @param {Node} vectorNode - The vector node to be packed
  25796. */
  25797. constructor( encoding, vectorNode ) {
  25798. super();
  25799. /**
  25800. * The vector to be packed.
  25801. *
  25802. * @type {Node}
  25803. */
  25804. this.vectorNode = vectorNode;
  25805. /**
  25806. * The numeric encoding.
  25807. *
  25808. * @type {string}
  25809. */
  25810. this.encoding = encoding;
  25811. /**
  25812. * This flag can be used for type testing.
  25813. *
  25814. * @type {boolean}
  25815. * @readonly
  25816. * @default true
  25817. */
  25818. this.isPackFloatNode = true;
  25819. }
  25820. generateNodeType() {
  25821. return 'uint';
  25822. }
  25823. generate( builder ) {
  25824. const inputType = this.vectorNode.getNodeType( builder );
  25825. return `${ builder.getFloatPackingMethod( this.encoding ) }(${ this.vectorNode.build( builder, inputType )})`;
  25826. }
  25827. }
  25828. /**
  25829. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  25830. * round(clamp(c, -1, +1) * 32767.0)
  25831. *
  25832. * @tsl
  25833. * @function
  25834. * @param {Node<vec2>} value - The 2-component vector to be packed
  25835. * @returns {Node}
  25836. */
  25837. const packSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'snorm' ).setParameterLength( 1 );
  25838. /**
  25839. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  25840. * round(clamp(c, 0, +1) * 65535.0)
  25841. *
  25842. * @tsl
  25843. * @function
  25844. * @param {Node<vec2>} value - The 2-component vector to be packed
  25845. * @returns {Node}
  25846. */
  25847. const packUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'unorm' ).setParameterLength( 1 );
  25848. /**
  25849. * Converts each component of the vec2 to 16-bit floating-point values. The results are packed into a single unsigned integer.
  25850. *
  25851. * @tsl
  25852. * @function
  25853. * @param {Node<vec2>} value - The 2-component vector to be packed
  25854. * @returns {Node}
  25855. */
  25856. const packHalf2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'float16' ).setParameterLength( 1 );
  25857. /**
  25858. * This node represents an operation that unpacks values from a 32-bit unsigned integer, reinterpreting the results as a floating-point vector
  25859. *
  25860. * @augments TempNode
  25861. */
  25862. class UnpackFloatNode extends TempNode {
  25863. static get type() {
  25864. return 'UnpackFloatNode';
  25865. }
  25866. /**
  25867. *
  25868. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the integer values are mapped to the float range
  25869. * @param {Node} uintNode - The uint node to be unpacked
  25870. */
  25871. constructor( encoding, uintNode ) {
  25872. super();
  25873. /**
  25874. * The unsigned integer to be unpacked.
  25875. *
  25876. * @type {Node}
  25877. */
  25878. this.uintNode = uintNode;
  25879. /**
  25880. * The numeric encoding.
  25881. *
  25882. * @type {string}
  25883. */
  25884. this.encoding = encoding;
  25885. /**
  25886. * This flag can be used for type testing.
  25887. *
  25888. * @type {boolean}
  25889. * @readonly
  25890. * @default true
  25891. */
  25892. this.isUnpackFloatNode = true;
  25893. }
  25894. generateNodeType() {
  25895. return 'vec2';
  25896. }
  25897. generate( builder ) {
  25898. const inputType = this.uintNode.getNodeType( builder );
  25899. return `${ builder.getFloatUnpackingMethod( this.encoding ) }(${ this.uintNode.build( builder, inputType )})`;
  25900. }
  25901. }
  25902. /**
  25903. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized signed integers. Returns a vec2 with both values.
  25904. *
  25905. * @tsl
  25906. * @function
  25907. * @param {Node<uint>} value - The unsigned integer to be unpacked
  25908. * @returns {Node}
  25909. */
  25910. const unpackSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'snorm' ).setParameterLength( 1 );
  25911. /**
  25912. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized unsigned integers. Returns a vec2 with both values.
  25913. *
  25914. * @tsl
  25915. * @function
  25916. * @param {Node<uint>} value - The unsigned integer to be unpacked
  25917. * @returns {Node}
  25918. */
  25919. const unpackUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'unorm' ).setParameterLength( 1 );
  25920. /**
  25921. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as 16-bit floating-point numbers. Returns a vec2 with both values.
  25922. *
  25923. * @tsl
  25924. * @function
  25925. * @param {Node<uint>} value - The unsigned integer to be unpacked
  25926. * @returns {Node}
  25927. */
  25928. const unpackHalf2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'float16' ).setParameterLength( 1 );
  25929. // https://github.com/cabbibo/glsl-tri-noise-3d
  25930. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  25931. return x.fract().sub( .5 ).abs();
  25932. } ).setLayout( {
  25933. name: 'tri',
  25934. type: 'float',
  25935. inputs: [
  25936. { name: 'x', type: 'float' }
  25937. ]
  25938. } );
  25939. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  25940. 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. ) ) ) ) );
  25941. } ).setLayout( {
  25942. name: 'tri3',
  25943. type: 'vec3',
  25944. inputs: [
  25945. { name: 'p', type: 'vec3' }
  25946. ]
  25947. } );
  25948. /**
  25949. * Generates a noise value from the given position, speed and time parameters.
  25950. *
  25951. * @tsl
  25952. * @function
  25953. * @param {Node<vec3>} position - The position.
  25954. * @param {Node<float>} speed - The speed.
  25955. * @param {Node<float>} time - The time.
  25956. * @return {Node<float>} The generated noise.
  25957. */
  25958. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  25959. const p = vec3( position ).toVar();
  25960. const z = float( 1.4 ).toVar();
  25961. const rz = float( 0.0 ).toVar();
  25962. const bp = vec3( p ).toVar();
  25963. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  25964. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  25965. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  25966. bp.mulAssign( 1.8 );
  25967. z.mulAssign( 1.5 );
  25968. p.mulAssign( 1.2 );
  25969. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  25970. rz.addAssign( t.div( z ) );
  25971. bp.addAssign( 0.14 );
  25972. } );
  25973. return rz;
  25974. } ).setLayout( {
  25975. name: 'triNoise3D',
  25976. type: 'float',
  25977. inputs: [
  25978. { name: 'position', type: 'vec3' },
  25979. { name: 'speed', type: 'float' },
  25980. { name: 'time', type: 'float' }
  25981. ]
  25982. } );
  25983. /**
  25984. * This class allows to define multiple overloaded versions
  25985. * of the same function. Depending on the parameters of the function
  25986. * call, the node picks the best-fit overloaded version.
  25987. *
  25988. * @augments Node
  25989. */
  25990. class FunctionOverloadingNode extends Node {
  25991. static get type() {
  25992. return 'FunctionOverloadingNode';
  25993. }
  25994. /**
  25995. * Constructs a new function overloading node.
  25996. *
  25997. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  25998. * @param {...Node} parametersNodes - A list of parameter nodes.
  25999. */
  26000. constructor( functionNodes = [], ...parametersNodes ) {
  26001. super();
  26002. /**
  26003. * Array of `Fn` function definitions.
  26004. *
  26005. * @type {Array<Function>}
  26006. */
  26007. this.functionNodes = functionNodes;
  26008. /**
  26009. * A list of parameter nodes.
  26010. *
  26011. * @type {Array<Node>}
  26012. */
  26013. this.parametersNodes = parametersNodes;
  26014. /**
  26015. * The selected overloaded function call.
  26016. *
  26017. * @private
  26018. * @type {ShaderCallNodeInternal}
  26019. */
  26020. this._candidateFn = null;
  26021. /**
  26022. * This node is marked as global.
  26023. *
  26024. * @type {boolean}
  26025. * @default true
  26026. */
  26027. this.global = true;
  26028. }
  26029. /**
  26030. * This method is overwritten since the node type is inferred from
  26031. * the function's return type.
  26032. *
  26033. * @param {NodeBuilder} builder - The current node builder.
  26034. * @return {string} The node type.
  26035. */
  26036. generateNodeType( builder ) {
  26037. const candidateFn = this.getCandidateFn( builder );
  26038. return candidateFn.shaderNode.layout.type;
  26039. }
  26040. /**
  26041. * Returns the candidate function for the current parameters.
  26042. *
  26043. * @param {NodeBuilder} builder - The current node builder.
  26044. * @return {FunctionNode} The candidate function.
  26045. */
  26046. getCandidateFn( builder ) {
  26047. const params = this.parametersNodes;
  26048. let candidateFn = this._candidateFn;
  26049. if ( candidateFn === null ) {
  26050. let bestCandidateFn = null;
  26051. let bestScore = -1;
  26052. for ( const functionNode of this.functionNodes ) {
  26053. const shaderNode = functionNode.shaderNode;
  26054. const layout = shaderNode.layout;
  26055. if ( layout === null ) {
  26056. throw new Error( 'THREE.FunctionOverloadingNode: FunctionNode must be a layout.' );
  26057. }
  26058. const inputs = layout.inputs;
  26059. if ( params.length === inputs.length ) {
  26060. let currentScore = 0;
  26061. for ( let i = 0; i < params.length; i ++ ) {
  26062. const param = params[ i ];
  26063. const input = inputs[ i ];
  26064. if ( param.getNodeType( builder ) === input.type ) {
  26065. currentScore ++;
  26066. }
  26067. }
  26068. if ( currentScore > bestScore ) {
  26069. bestCandidateFn = functionNode;
  26070. bestScore = currentScore;
  26071. }
  26072. }
  26073. }
  26074. this._candidateFn = candidateFn = bestCandidateFn;
  26075. }
  26076. return candidateFn;
  26077. }
  26078. /**
  26079. * Sets up the node for the current parameters.
  26080. *
  26081. * @param {NodeBuilder} builder - The current node builder.
  26082. * @return {Node} The setup node.
  26083. */
  26084. setup( builder ) {
  26085. const candidateFn = this.getCandidateFn( builder );
  26086. return candidateFn( ...this.parametersNodes );
  26087. }
  26088. }
  26089. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  26090. /**
  26091. * TSL function for creating a function overloading node.
  26092. *
  26093. * @tsl
  26094. * @function
  26095. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  26096. * @returns {FunctionOverloadingNode}
  26097. */
  26098. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  26099. /**
  26100. * Represents the elapsed time in seconds.
  26101. *
  26102. * @tsl
  26103. * @type {UniformNode<float>}
  26104. */
  26105. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  26106. /**
  26107. * Represents the delta time in seconds.
  26108. *
  26109. * @tsl
  26110. * @type {UniformNode<float>}
  26111. */
  26112. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  26113. /**
  26114. * Represents the current frame ID.
  26115. *
  26116. * @tsl
  26117. * @type {UniformNode<uint>}
  26118. */
  26119. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  26120. /**
  26121. * Generates a sine wave oscillation based on a timer.
  26122. *
  26123. * @tsl
  26124. * @function
  26125. * @param {Node<float>} t - The timer to generate the oscillation with.
  26126. * @return {Node<float>} The oscillation node.
  26127. */
  26128. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  26129. /**
  26130. * Generates a square wave oscillation based on a timer.
  26131. *
  26132. * @tsl
  26133. * @function
  26134. * @param {Node<float>} t - The timer to generate the oscillation with.
  26135. * @return {Node<float>} The oscillation node.
  26136. */
  26137. const oscSquare = ( t = time ) => t.fract().round();
  26138. /**
  26139. * Generates a triangle wave oscillation based on a timer.
  26140. *
  26141. * @tsl
  26142. * @function
  26143. * @param {Node<float>} t - The timer to generate the oscillation with.
  26144. * @return {Node<float>} The oscillation node.
  26145. */
  26146. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  26147. /**
  26148. * Generates a sawtooth wave oscillation based on a timer.
  26149. *
  26150. * @tsl
  26151. * @function
  26152. * @param {Node<float>} t - The timer to generate the oscillation with.
  26153. * @return {Node<float>} The oscillation node.
  26154. */
  26155. const oscSawtooth = ( t = time ) => t.fract();
  26156. /**
  26157. * Replaces the default UV coordinates used in texture lookups.
  26158. *
  26159. * ```js
  26160. *material.contextNode = replaceDefaultUV( ( textureNode ) => {
  26161. *
  26162. * // ...
  26163. * return customUVCoordinates;
  26164. *
  26165. *} );
  26166. *```
  26167. *
  26168. * @tsl
  26169. * @function
  26170. * @param {function(Node):Node<vec2>|Node<vec2>} callback - A callback that receives the texture node
  26171. * and must return the new uv coordinates.
  26172. * @param {Node} [node=null] - An optional node to which the context will be applied.
  26173. * @return {ContextNode} A context node that replaces the default UV coordinates.
  26174. */
  26175. function replaceDefaultUV( callback, node = null ) {
  26176. const getUV = typeof callback === 'function' ? callback : () => callback;
  26177. return context( node, { getUV } );
  26178. }
  26179. /**
  26180. * Rotates the given uv coordinates around a center point
  26181. *
  26182. * @tsl
  26183. * @function
  26184. * @param {Node<vec2>} uv - The uv coordinates.
  26185. * @param {Node<float>} rotation - The rotation defined in radians.
  26186. * @param {Node<vec2>} center - The center of rotation
  26187. * @return {Node<vec2>} The rotated uv coordinates.
  26188. */
  26189. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  26190. return rotate( uv.sub( center ), rotation ).add( center );
  26191. } );
  26192. /**
  26193. * Applies a spherical warping effect to the given uv coordinates.
  26194. *
  26195. * @tsl
  26196. * @function
  26197. * @param {Node<vec2>} uv - The uv coordinates.
  26198. * @param {Node<float>} strength - The strength of the effect.
  26199. * @param {Node<vec2>} center - The center point
  26200. * @return {Node<vec2>} The updated uv coordinates.
  26201. */
  26202. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  26203. const delta = uv.sub( center );
  26204. const delta2 = delta.dot( delta );
  26205. const delta4 = delta2.mul( delta2 );
  26206. const deltaOffset = delta4.mul( strength );
  26207. return uv.add( delta.mul( deltaOffset ) );
  26208. } );
  26209. /**
  26210. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  26211. * oriented always towards the camera.
  26212. *
  26213. * ```js
  26214. * material.vertexNode = billboarding();
  26215. * ```
  26216. *
  26217. * @tsl
  26218. * @function
  26219. * @param {Object} config - The configuration object.
  26220. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  26221. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  26222. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  26223. * @return {Node<vec3>} The updated vertex position in clip space.
  26224. */
  26225. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  26226. let worldMatrix;
  26227. if ( position !== null ) {
  26228. worldMatrix = modelWorldMatrix.toVar();
  26229. worldMatrix[ 3 ][ 0 ] = position.x;
  26230. worldMatrix[ 3 ][ 1 ] = position.y;
  26231. worldMatrix[ 3 ][ 2 ] = position.z;
  26232. } else {
  26233. worldMatrix = modelWorldMatrix;
  26234. }
  26235. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  26236. if ( defined( horizontal ) ) {
  26237. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  26238. modelViewMatrix[ 0 ][ 1 ] = 0;
  26239. modelViewMatrix[ 0 ][ 2 ] = 0;
  26240. }
  26241. if ( defined( vertical ) ) {
  26242. modelViewMatrix[ 1 ][ 0 ] = 0;
  26243. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  26244. modelViewMatrix[ 1 ][ 2 ] = 0;
  26245. }
  26246. modelViewMatrix[ 2 ][ 0 ] = 0;
  26247. modelViewMatrix[ 2 ][ 1 ] = 0;
  26248. modelViewMatrix[ 2 ][ 2 ] = 1;
  26249. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  26250. } );
  26251. /**
  26252. * A special version of a screen uv function that involves a depth comparison
  26253. * when computing the final uvs. The function mitigates visual errors when
  26254. * using viewport texture nodes for refraction purposes. Without this function
  26255. * objects in front of a refractive surface might appear on the refractive surface
  26256. * which is incorrect.
  26257. *
  26258. * @tsl
  26259. * @function
  26260. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  26261. * @return {Node<vec2>} The update uv coordinates.
  26262. */
  26263. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  26264. const depth = linearDepth();
  26265. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  26266. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  26267. return finalUV;
  26268. } );
  26269. /**
  26270. * TSL function for computing texture coordinates for animated sprite sheets.
  26271. *
  26272. * ```js
  26273. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  26274. *
  26275. * material.colorNode = texture( spriteSheet, uvNode );
  26276. * ```
  26277. *
  26278. * @tsl
  26279. * @function
  26280. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  26281. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  26282. * @param {?Node<float>} [frameNode=float(0)] - The node that defines the current frame/sprite.
  26283. * @returns {Node<vec2>}
  26284. */
  26285. const spritesheetUV = /*@__PURE__*/ Fn( ( [ countNode, uvNode = uv$1(), frameNode = float( 0 ) ] ) => {
  26286. const width = countNode.x;
  26287. const height = countNode.y;
  26288. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  26289. const column = frameNum.mod( width );
  26290. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  26291. const scale = countNode.reciprocal();
  26292. const uvFrameOffset = vec2( column, row );
  26293. return uvNode.add( uvFrameOffset ).mul( scale );
  26294. } );
  26295. /**
  26296. * TSL function for creating a triplanar textures node.
  26297. *
  26298. * Can be used for triplanar texture mapping.
  26299. *
  26300. * ```js
  26301. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  26302. * ```
  26303. *
  26304. * @tsl
  26305. * @function
  26306. * @param {Node} textureXNode - First texture node.
  26307. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  26308. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  26309. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  26310. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  26311. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  26312. * @returns {Node<vec4>}
  26313. */
  26314. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  26315. // Reference: https://github.com/keijiro/StandardTriplanar
  26316. // Blending factor of triplanar mapping
  26317. let bf = normalNode.abs().normalize();
  26318. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  26319. // Triplanar mapping
  26320. const tx = positionNode.yz.mul( scaleNode );
  26321. const ty = positionNode.zx.mul( scaleNode );
  26322. const tz = positionNode.xy.mul( scaleNode );
  26323. // Base color
  26324. const textureX = textureXNode.value;
  26325. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  26326. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  26327. const cx = texture( textureX, tx ).mul( bf.x );
  26328. const cy = texture( textureY, ty ).mul( bf.y );
  26329. const cz = texture( textureZ, tz ).mul( bf.z );
  26330. return add( cx, cy, cz );
  26331. } );
  26332. /**
  26333. * TSL function for creating a triplanar textures node.
  26334. *
  26335. * @tsl
  26336. * @function
  26337. * @param {Node} textureXNode - First texture node.
  26338. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  26339. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  26340. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  26341. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  26342. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  26343. * @returns {Node<vec4>}
  26344. */
  26345. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  26346. const _reflectorPlane = new Plane();
  26347. const _normal = new Vector3();
  26348. const _reflectorWorldPosition = new Vector3();
  26349. const _cameraWorldPosition = new Vector3();
  26350. const _rotationMatrix = new Matrix4();
  26351. const _lookAtPosition = new Vector3( 0, 0, -1 );
  26352. const clipPlane = new Vector4();
  26353. const _view = new Vector3();
  26354. const _target = new Vector3();
  26355. const _q = new Vector4();
  26356. const _size$2 = new Vector2();
  26357. const _defaultRT = new RenderTarget();
  26358. const _defaultUV = screenUV.flipX();
  26359. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  26360. let _inReflector = false;
  26361. /**
  26362. * This node can be used to implement mirror-like flat reflective surfaces.
  26363. *
  26364. * ```js
  26365. * const groundReflector = reflector();
  26366. * material.colorNode = groundReflector;
  26367. *
  26368. * const plane = new Mesh( geometry, material );
  26369. * plane.add( groundReflector.target );
  26370. * ```
  26371. *
  26372. * @augments TextureNode
  26373. */
  26374. class ReflectorNode extends TextureNode {
  26375. static get type() {
  26376. return 'ReflectorNode';
  26377. }
  26378. /**
  26379. * Constructs a new reflector node.
  26380. *
  26381. * @param {Object} [parameters={}] - An object holding configuration parameters.
  26382. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  26383. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  26384. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  26385. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  26386. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  26387. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  26388. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  26389. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  26390. */
  26391. constructor( parameters = {} ) {
  26392. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  26393. /**
  26394. * A reference to the internal reflector base node which holds the actual implementation.
  26395. *
  26396. * @private
  26397. * @type {ReflectorBaseNode}
  26398. * @default ReflectorBaseNode
  26399. */
  26400. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  26401. /**
  26402. * A reference to the internal depth node.
  26403. *
  26404. * @private
  26405. * @type {?Node}
  26406. * @default null
  26407. */
  26408. this._depthNode = null;
  26409. this.setUpdateMatrix( false );
  26410. }
  26411. /**
  26412. * A reference to the internal reflector node.
  26413. *
  26414. * @type {ReflectorBaseNode}
  26415. */
  26416. get reflector() {
  26417. return this._reflectorBaseNode;
  26418. }
  26419. /**
  26420. * A reference to 3D object the reflector is linked to.
  26421. *
  26422. * @type {Object3D}
  26423. */
  26424. get target() {
  26425. return this._reflectorBaseNode.target;
  26426. }
  26427. /**
  26428. * Returns a node representing the mirror's depth. That can be used
  26429. * to implement more advanced reflection effects like distance attenuation.
  26430. *
  26431. * @return {Node} The depth node.
  26432. */
  26433. getDepthNode() {
  26434. if ( this._depthNode === null ) {
  26435. if ( this._reflectorBaseNode.depth !== true ) {
  26436. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  26437. }
  26438. this._depthNode = new ReflectorNode( {
  26439. defaultTexture: _defaultRT.depthTexture,
  26440. reflector: this._reflectorBaseNode
  26441. } );
  26442. }
  26443. return this._depthNode;
  26444. }
  26445. setup( builder ) {
  26446. // ignore if used in post-processing
  26447. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  26448. return super.setup( builder );
  26449. }
  26450. clone() {
  26451. const newNode = new this.constructor( this.reflectorNode );
  26452. newNode.uvNode = this.uvNode;
  26453. newNode.levelNode = this.levelNode;
  26454. newNode.biasNode = this.biasNode;
  26455. newNode.sampler = this.sampler;
  26456. newNode.depthNode = this.depthNode;
  26457. newNode.compareNode = this.compareNode;
  26458. newNode.gradNode = this.gradNode;
  26459. newNode.gatherNode = this.gatherNode;
  26460. newNode.offsetNode = this.offsetNode;
  26461. newNode._reflectorBaseNode = this._reflectorBaseNode;
  26462. return newNode;
  26463. }
  26464. /**
  26465. * Frees internal resources. Should be called when the node is no longer in use.
  26466. */
  26467. dispose() {
  26468. super.dispose();
  26469. this._reflectorBaseNode.dispose();
  26470. }
  26471. }
  26472. /**
  26473. * Holds the actual implementation of the reflector.
  26474. *
  26475. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  26476. * in `ReflectorNode`, see #29619.
  26477. *
  26478. * @private
  26479. * @augments Node
  26480. */
  26481. class ReflectorBaseNode extends Node {
  26482. static get type() {
  26483. return 'ReflectorBaseNode';
  26484. }
  26485. /**
  26486. * Constructs a new reflector base node.
  26487. *
  26488. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  26489. * @param {Object} [parameters={}] - An object holding configuration parameters.
  26490. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  26491. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  26492. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  26493. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  26494. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  26495. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  26496. */
  26497. constructor( textureNode, parameters = {} ) {
  26498. super();
  26499. const {
  26500. target = new Object3D(),
  26501. resolutionScale = 1,
  26502. generateMipmaps = false,
  26503. bounces = true,
  26504. depth = false,
  26505. samples = 0
  26506. } = parameters;
  26507. /**
  26508. * Represents the rendered reflections as a texture node.
  26509. *
  26510. * @type {TextureNode}
  26511. */
  26512. this.textureNode = textureNode;
  26513. /**
  26514. * The 3D object the reflector is linked to.
  26515. *
  26516. * @type {Object3D}
  26517. * @default {new Object3D()}
  26518. */
  26519. this.target = target;
  26520. /**
  26521. * The resolution scale.
  26522. *
  26523. * @type {number}
  26524. * @default {1}
  26525. */
  26526. this.resolutionScale = resolutionScale;
  26527. if ( parameters.resolution !== undefined ) {
  26528. warnOnce( 'ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".' ); // @deprecated r180
  26529. this.resolutionScale = parameters.resolution;
  26530. }
  26531. /**
  26532. * Whether mipmaps should be generated or not.
  26533. *
  26534. * @type {boolean}
  26535. * @default {false}
  26536. */
  26537. this.generateMipmaps = generateMipmaps;
  26538. /**
  26539. * Whether reflectors can render other reflector nodes or not.
  26540. *
  26541. * @type {boolean}
  26542. * @default {true}
  26543. */
  26544. this.bounces = bounces;
  26545. /**
  26546. * Whether depth data should be generated or not.
  26547. *
  26548. * @type {boolean}
  26549. * @default {false}
  26550. */
  26551. this.depth = depth;
  26552. /**
  26553. * The number of anti-aliasing samples for the render-target
  26554. *
  26555. * @type {number}
  26556. * @default {0}
  26557. */
  26558. this.samples = samples;
  26559. /**
  26560. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  26561. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  26562. *
  26563. * @type {string}
  26564. * @default 'render'
  26565. */
  26566. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  26567. /**
  26568. * Weak map for managing virtual cameras.
  26569. *
  26570. * @type {WeakMap<Camera, Camera>}
  26571. */
  26572. this.virtualCameras = new WeakMap();
  26573. /**
  26574. * Weak map for managing render targets.
  26575. *
  26576. * @type {Map<Camera, RenderTarget>}
  26577. */
  26578. this.renderTargets = new Map();
  26579. /**
  26580. * Force render even if reflector is facing away from camera.
  26581. *
  26582. * @type {boolean}
  26583. * @default {false}
  26584. */
  26585. this.forceUpdate = false;
  26586. /**
  26587. * Whether the reflector has been rendered or not.
  26588. *
  26589. * When the reflector is facing away from the camera,
  26590. * this flag is set to `false` and the texture will be empty(black).
  26591. *
  26592. * @type {boolean}
  26593. * @default {false}
  26594. */
  26595. this.hasOutput = false;
  26596. }
  26597. /**
  26598. * Updates the resolution of the internal render target.
  26599. *
  26600. * @private
  26601. * @param {RenderTarget} renderTarget - The render target to resize.
  26602. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  26603. */
  26604. _updateResolution( renderTarget, renderer ) {
  26605. const resolution = this.resolutionScale;
  26606. renderer.getDrawingBufferSize( _size$2 );
  26607. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  26608. }
  26609. setup( builder ) {
  26610. this._updateResolution( _defaultRT, builder.renderer );
  26611. return super.setup( builder );
  26612. }
  26613. /**
  26614. * Frees internal resources. Should be called when the node is no longer in use.
  26615. */
  26616. dispose() {
  26617. super.dispose();
  26618. for ( const renderTarget of this.renderTargets.values() ) {
  26619. renderTarget.dispose();
  26620. }
  26621. }
  26622. /**
  26623. * Returns a virtual camera for the given camera. The virtual camera is used to
  26624. * render the scene from the reflector's view so correct reflections can be produced.
  26625. *
  26626. * @param {Camera} camera - The scene's camera.
  26627. * @return {Camera} The corresponding virtual camera.
  26628. */
  26629. getVirtualCamera( camera ) {
  26630. let virtualCamera = this.virtualCameras.get( camera );
  26631. if ( virtualCamera === undefined ) {
  26632. virtualCamera = camera.clone();
  26633. this.virtualCameras.set( camera, virtualCamera );
  26634. }
  26635. return virtualCamera;
  26636. }
  26637. /**
  26638. * Returns a render target for the given camera. The reflections are rendered
  26639. * into this render target.
  26640. *
  26641. * @param {Camera} camera - The scene's camera.
  26642. * @return {RenderTarget} The render target.
  26643. */
  26644. getRenderTarget( camera ) {
  26645. let renderTarget = this.renderTargets.get( camera );
  26646. if ( renderTarget === undefined ) {
  26647. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  26648. if ( this.generateMipmaps === true ) {
  26649. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  26650. renderTarget.texture.generateMipmaps = true;
  26651. }
  26652. if ( this.depth === true ) {
  26653. renderTarget.depthTexture = new DepthTexture();
  26654. }
  26655. this.renderTargets.set( camera, renderTarget );
  26656. }
  26657. return renderTarget;
  26658. }
  26659. updateBefore( frame ) {
  26660. if ( this.bounces === false && _inReflector ) return false;
  26661. _inReflector = true;
  26662. const { scene, camera, renderer, material } = frame;
  26663. const { target } = this;
  26664. const virtualCamera = this.getVirtualCamera( camera );
  26665. const renderTarget = this.getRenderTarget( virtualCamera );
  26666. renderer.getDrawingBufferSize( _size$2 );
  26667. this._updateResolution( renderTarget, renderer );
  26668. //
  26669. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  26670. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  26671. _rotationMatrix.extractRotation( target.matrixWorld );
  26672. _normal.set( 0, 0, 1 );
  26673. _normal.applyMatrix4( _rotationMatrix );
  26674. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  26675. // Avoid rendering when reflector is facing away unless forcing an update
  26676. const isFacingAway = _view.dot( _normal ) > 0;
  26677. let needsClear = false;
  26678. if ( isFacingAway === true && this.forceUpdate === false ) {
  26679. if ( this.hasOutput === false ) {
  26680. _inReflector = false;
  26681. return;
  26682. }
  26683. needsClear = true;
  26684. }
  26685. _view.reflect( _normal ).negate();
  26686. _view.add( _reflectorWorldPosition );
  26687. _rotationMatrix.extractRotation( camera.matrixWorld );
  26688. _lookAtPosition.set( 0, 0, -1 );
  26689. _lookAtPosition.applyMatrix4( _rotationMatrix );
  26690. _lookAtPosition.add( _cameraWorldPosition );
  26691. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  26692. _target.reflect( _normal ).negate();
  26693. _target.add( _reflectorWorldPosition );
  26694. //
  26695. virtualCamera.coordinateSystem = camera.coordinateSystem;
  26696. virtualCamera.position.copy( _view );
  26697. virtualCamera.up.set( 0, 1, 0 );
  26698. virtualCamera.up.applyMatrix4( _rotationMatrix );
  26699. virtualCamera.up.reflect( _normal );
  26700. virtualCamera.lookAt( _target );
  26701. virtualCamera.near = camera.near;
  26702. virtualCamera.far = camera.far;
  26703. virtualCamera.updateMatrixWorld();
  26704. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  26705. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  26706. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  26707. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  26708. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  26709. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  26710. const projectionMatrix = virtualCamera.projectionMatrix;
  26711. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  26712. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  26713. _q.z = -1;
  26714. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  26715. // Calculate the scaled plane vector
  26716. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  26717. const clipBias = 0;
  26718. // Replacing the third row of the projection matrix
  26719. projectionMatrix.elements[ 2 ] = clipPlane.x;
  26720. projectionMatrix.elements[ 6 ] = clipPlane.y;
  26721. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  26722. projectionMatrix.elements[ 14 ] = clipPlane.w;
  26723. //
  26724. this.textureNode.value = renderTarget.texture;
  26725. if ( this.depth === true ) {
  26726. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  26727. }
  26728. material.visible = false;
  26729. const currentRenderTarget = renderer.getRenderTarget();
  26730. const currentMRT = renderer.getMRT();
  26731. const currentAutoClear = renderer.autoClear;
  26732. renderer.setMRT( null );
  26733. renderer.setRenderTarget( renderTarget );
  26734. renderer.autoClear = true;
  26735. const previousName = scene.name;
  26736. scene.name = ( scene.name || 'Scene' ) + ' [ Reflector ]'; // TODO: Add bounce index
  26737. if ( needsClear ) {
  26738. renderer.clear();
  26739. this.hasOutput = false;
  26740. } else {
  26741. renderer.render( scene, virtualCamera );
  26742. this.hasOutput = true;
  26743. }
  26744. scene.name = previousName;
  26745. renderer.setMRT( currentMRT );
  26746. renderer.setRenderTarget( currentRenderTarget );
  26747. renderer.autoClear = currentAutoClear;
  26748. material.visible = true;
  26749. _inReflector = false;
  26750. this.forceUpdate = false;
  26751. }
  26752. /**
  26753. * The resolution scale.
  26754. *
  26755. * @deprecated
  26756. * @type {number}
  26757. * @default {1}
  26758. */
  26759. get resolution() {
  26760. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  26761. return this.resolutionScale;
  26762. }
  26763. set resolution( value ) {
  26764. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  26765. this.resolutionScale = value;
  26766. }
  26767. }
  26768. /**
  26769. * TSL function for creating a reflector node.
  26770. *
  26771. * @tsl
  26772. * @function
  26773. * @param {Object} [parameters={}] - An object holding configuration parameters.
  26774. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  26775. * @param {number} [parameters.resolution=1] - The resolution scale.
  26776. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  26777. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  26778. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  26779. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  26780. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  26781. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  26782. * @returns {ReflectorNode}
  26783. */
  26784. const reflector = ( parameters ) => new ReflectorNode( parameters );
  26785. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  26786. /**
  26787. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  26788. *
  26789. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  26790. *
  26791. * @private
  26792. * @augments BufferGeometry
  26793. */
  26794. class QuadGeometry extends BufferGeometry {
  26795. /**
  26796. * Constructs a new quad geometry.
  26797. *
  26798. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  26799. */
  26800. constructor( flipY = false ) {
  26801. super();
  26802. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  26803. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  26804. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  26805. }
  26806. }
  26807. const _geometry = /*@__PURE__*/ new QuadGeometry();
  26808. /**
  26809. * This module is a helper for passes which need to render a full
  26810. * screen effect which is quite common in context of post processing.
  26811. *
  26812. * The intended usage is to reuse a single quad mesh for rendering
  26813. * subsequent passes by just reassigning the `material` reference.
  26814. *
  26815. * Note: This module can only be used with `WebGPURenderer`.
  26816. *
  26817. * @augments Mesh
  26818. */
  26819. class QuadMesh extends Mesh {
  26820. /**
  26821. * Constructs a new quad mesh.
  26822. *
  26823. * @param {?Material} [material=null] - The material to render the quad mesh with.
  26824. */
  26825. constructor( material = null ) {
  26826. super( _geometry, material );
  26827. /**
  26828. * The camera to render the quad mesh with.
  26829. *
  26830. * @type {OrthographicCamera}
  26831. * @readonly
  26832. */
  26833. this.camera = _camera;
  26834. /**
  26835. * This flag can be used for type testing.
  26836. *
  26837. * @type {boolean}
  26838. * @readonly
  26839. * @default true
  26840. */
  26841. this.isQuadMesh = true;
  26842. }
  26843. /**
  26844. * Async version of `render()`.
  26845. *
  26846. * @async
  26847. * @deprecated
  26848. * @param {Renderer} renderer - The renderer.
  26849. * @return {Promise} A Promise that resolves when the render has been finished.
  26850. */
  26851. async renderAsync( renderer ) {
  26852. warnOnce( 'QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  26853. await renderer.init();
  26854. renderer.render( this, _camera );
  26855. }
  26856. /**
  26857. * Renders the quad mesh
  26858. *
  26859. * @param {Renderer} renderer - The renderer.
  26860. */
  26861. render( renderer ) {
  26862. renderer.render( this, _camera );
  26863. }
  26864. }
  26865. const _size$1 = /*@__PURE__*/ new Vector2();
  26866. /**
  26867. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  26868. * This module is especially relevant in context of post processing where certain nodes require
  26869. * texture input for their effects. With the helper function `convertToTexture()` which is based
  26870. * on this module, the node system can automatically ensure texture input if required.
  26871. *
  26872. * @augments TextureNode
  26873. */
  26874. class RTTNode extends TextureNode {
  26875. static get type() {
  26876. return 'RTTNode';
  26877. }
  26878. /**
  26879. * Constructs a new RTT node.
  26880. *
  26881. * @param {Node} node - The node to render a texture with.
  26882. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  26883. * @param {?number} [height=null] - The height of the internal render target.
  26884. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  26885. */
  26886. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  26887. const renderTarget = new RenderTarget( width, height, options );
  26888. super( renderTarget.texture, uv$1() );
  26889. /**
  26890. * This flag can be used for type testing.
  26891. *
  26892. * @type {boolean}
  26893. * @readonly
  26894. * @default true
  26895. */
  26896. this.isRTTNode = true;
  26897. /**
  26898. * The node to render a texture with.
  26899. *
  26900. * @type {Node}
  26901. */
  26902. this.node = node;
  26903. /**
  26904. * The width of the internal render target.
  26905. * If not width is applied, the render target is automatically resized.
  26906. *
  26907. * @type {?number}
  26908. * @default null
  26909. */
  26910. this.width = width;
  26911. /**
  26912. * The height of the internal render target.
  26913. *
  26914. * @type {?number}
  26915. * @default null
  26916. */
  26917. this.height = height;
  26918. /**
  26919. * The render target
  26920. *
  26921. * @type {RenderTarget}
  26922. */
  26923. this.renderTarget = renderTarget;
  26924. /**
  26925. * Whether the texture requires an update or not.
  26926. *
  26927. * @type {boolean}
  26928. * @default true
  26929. */
  26930. this.textureNeedsUpdate = true;
  26931. /**
  26932. * Whether the texture should automatically be updated or not.
  26933. *
  26934. * @type {boolean}
  26935. * @default true
  26936. */
  26937. this.autoUpdate = true;
  26938. /**
  26939. * The resolution scale
  26940. *
  26941. * @private
  26942. * @type {number}
  26943. * @default 1
  26944. */
  26945. this._resolutionScale = 1;
  26946. /**
  26947. * The node which is used with the quad mesh for RTT.
  26948. *
  26949. * @private
  26950. * @type {Node}
  26951. * @default null
  26952. */
  26953. this._rttNode = null;
  26954. /**
  26955. * The internal quad mesh for RTT.
  26956. *
  26957. * @private
  26958. * @type {QuadMesh}
  26959. */
  26960. this._quadMesh = new QuadMesh( new NodeMaterial() );
  26961. /**
  26962. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  26963. * the texture once per render in its {@link RTTNode#updateBefore} method.
  26964. *
  26965. * @type {string}
  26966. * @default 'render'
  26967. */
  26968. this.updateBeforeType = NodeUpdateType.RENDER;
  26969. }
  26970. /**
  26971. * Whether the internal render target should automatically be resized or not.
  26972. *
  26973. * @type {boolean}
  26974. * @readonly
  26975. * @default true
  26976. */
  26977. get autoResize() {
  26978. return this.width === null;
  26979. }
  26980. setup( builder ) {
  26981. this._rttNode = this.node.context( builder.getSharedContext() );
  26982. this._quadMesh.material.name = 'RTT';
  26983. this._quadMesh.material.needsUpdate = true;
  26984. return super.setup( builder );
  26985. }
  26986. /**
  26987. * Sets the size of the internal render target
  26988. *
  26989. * @param {number} width - The width to set.
  26990. * @param {number} height - The width to set.
  26991. */
  26992. setSize( width, height ) {
  26993. const effectiveWidth = Math.floor( width * this._resolutionScale );
  26994. const effectiveHeight = Math.floor( height * this._resolutionScale );
  26995. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  26996. this.textureNeedsUpdate = true;
  26997. }
  26998. /**
  26999. * Sets the resolution scale.
  27000. * The resolution scale is a factor that is multiplied with the renderer's width and height.
  27001. *
  27002. * @param {number} resolutionScale - The resolution scale to set. A value of `1` means full resolution.
  27003. * @returns {RTTNode} A reference to this node.
  27004. */
  27005. setResolutionScale( resolutionScale ) {
  27006. this._resolutionScale = resolutionScale;
  27007. if ( this.autoResize === false ) {
  27008. this.setSize( this.width, this.height );
  27009. }
  27010. return this;
  27011. }
  27012. /**
  27013. * Gets the resolution scale.
  27014. *
  27015. * @returns {number} The resolution scale.
  27016. */
  27017. getResolutionScale() {
  27018. return this._resolutionScale;
  27019. }
  27020. updateBefore( { renderer } ) {
  27021. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  27022. this.textureNeedsUpdate = false;
  27023. //
  27024. const currentRenderTarget = renderer.getRenderTarget();
  27025. if ( this.autoResize === true ) {
  27026. const size = renderer.getDrawingBufferSize( _size$1 );
  27027. const effectiveWidth = Math.floor( size.width * this._resolutionScale );
  27028. const effectiveHeight = Math.floor( size.height * this._resolutionScale );
  27029. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  27030. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  27031. this.textureNeedsUpdate = true;
  27032. }
  27033. }
  27034. //
  27035. let name = 'RTT';
  27036. if ( this.node.name ) {
  27037. name = this.node.name + ' [ ' + name + ' ]';
  27038. }
  27039. this._quadMesh.material.fragmentNode = this._rttNode;
  27040. this._quadMesh.name = name;
  27041. //
  27042. renderer.setRenderTarget( this.renderTarget );
  27043. this._quadMesh.render( renderer );
  27044. renderer.setRenderTarget( currentRenderTarget );
  27045. }
  27046. clone() {
  27047. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  27048. newNode.sampler = this.sampler;
  27049. newNode.referenceNode = this;
  27050. return newNode;
  27051. }
  27052. }
  27053. /**
  27054. * TSL function for creating a RTT node.
  27055. *
  27056. * @tsl
  27057. * @function
  27058. * @param {Node} node - The node to render a texture with.
  27059. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  27060. * @param {?number} [height=null] - The height of the internal render target.
  27061. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  27062. * @returns {RTTNode}
  27063. */
  27064. const rtt = ( node, ...params ) => new RTTNode( nodeObject( node ), ...params );
  27065. /**
  27066. * TSL function for converting nodes to textures nodes.
  27067. *
  27068. * @tsl
  27069. * @function
  27070. * @param {Node} node - The node to render a texture with.
  27071. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  27072. * @param {?number} [height=null] - The height of the internal render target.
  27073. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  27074. * @returns {RTTNode}
  27075. */
  27076. const convertToTexture = ( node, ...params ) => {
  27077. if ( node.isSampleNode || node.isTextureNode ) return node;
  27078. if ( node.isPassNode ) return node.getTextureNode();
  27079. return rtt( node, ...params );
  27080. };
  27081. /**
  27082. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  27083. * depth value and the camera's inverse projection matrix.
  27084. *
  27085. * @tsl
  27086. * @function
  27087. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  27088. * @param {Node<float>} depth - The fragment's depth value.
  27089. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  27090. * @return {Node<vec3>} The fragments position in view space.
  27091. */
  27092. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  27093. let clipSpacePosition;
  27094. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  27095. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  27096. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  27097. } else {
  27098. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  27099. }
  27100. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  27101. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  27102. } );
  27103. /**
  27104. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  27105. * and the camera's projection matrix
  27106. *
  27107. * @tsl
  27108. * @function
  27109. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  27110. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  27111. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  27112. */
  27113. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  27114. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  27115. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  27116. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  27117. } );
  27118. /**
  27119. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  27120. * target is available or if flat surface normals are required.
  27121. *
  27122. * @tsl
  27123. * @function
  27124. * @param {Node<vec2>} uv - The texture coordinate.
  27125. * @param {DepthTexture} depthTexture - The depth texture.
  27126. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  27127. * @return {Node<vec3>} The computed normal vector.
  27128. */
  27129. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  27130. const size = textureSize( textureLoad( depthTexture ) );
  27131. const p = ivec2( uv.mul( size ) ).toVar();
  27132. const c0 = textureLoad( depthTexture, p ).toVar();
  27133. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  27134. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  27135. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  27136. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  27137. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  27138. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  27139. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  27140. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  27141. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  27142. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  27143. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  27144. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  27145. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  27146. 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 ) ) );
  27147. 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 ) ) );
  27148. return normalize( cross( dpdx, dpdy ) );
  27149. } );
  27150. /**
  27151. * Interleaved Gradient Noise (IGN) from Jimenez 2014.
  27152. *
  27153. * IGN has "low discrepancy" resulting in evenly distributed samples. It's superior compared to
  27154. * default white noise, blue noise or Bayer.
  27155. *
  27156. * References:
  27157. * - {@link https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare/}
  27158. * - {@link https://blog.demofox.org/2022/01/01/interleaved-gradient-noise-a-different-kind-of-low-discrepancy-sequence/}
  27159. *
  27160. * @tsl
  27161. * @function
  27162. * @param {Node<vec2>} position - The input position, usually screen coordinates.
  27163. * @return {Node<float>} The noise value.
  27164. */
  27165. const interleavedGradientNoise = Fn( ( [ position ] ) => {
  27166. return fract( float( 52.9829189 ).mul( fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ) );
  27167. } ).setLayout( {
  27168. name: 'interleavedGradientNoise',
  27169. type: 'float',
  27170. inputs: [
  27171. { name: 'position', type: 'vec2' }
  27172. ]
  27173. } );
  27174. /**
  27175. * Vogel disk sampling for uniform circular distribution.
  27176. *
  27177. * This function generates sample points distributed uniformly on a disk using the golden angle,
  27178. * resulting in an efficient low-discrepancy sequence for sampling. The rotation parameter (phi)
  27179. * allows randomizing the pattern per-pixel when combined with IGN.
  27180. *
  27181. * @tsl
  27182. * @function
  27183. * @param {Node<int>} sampleIndex - The index of the current sample (0-based).
  27184. * @param {Node<int>} samplesCount - The total number of samples.
  27185. * @param {Node<float>} phi - Rotation angle in radians (typically from IGN * 2π).
  27186. * @return {Node<vec2>} A 2D point on the unit disk.
  27187. */
  27188. const vogelDiskSample = Fn( ( [ sampleIndex, samplesCount, phi ] ) => {
  27189. const goldenAngle = float( 2.399963229728653 ); // 2π * (2 - φ) where φ is golden ratio
  27190. const r = sqrt( float( sampleIndex ).add( 0.5 ).div( float( samplesCount ) ) );
  27191. const theta = float( sampleIndex ).mul( goldenAngle ).add( phi );
  27192. return vec2( cos( theta ), sin( theta ) ).mul( r );
  27193. } ).setLayout( {
  27194. name: 'vogelDiskSample',
  27195. type: 'vec2',
  27196. inputs: [
  27197. { name: 'sampleIndex', type: 'int' },
  27198. { name: 'samplesCount', type: 'int' },
  27199. { name: 'phi', type: 'float' }
  27200. ]
  27201. } );
  27202. /**
  27203. * Class representing a node that samples a value using a provided callback function.
  27204. *
  27205. * @extends Node
  27206. */
  27207. class SampleNode extends Node {
  27208. /**
  27209. * Returns the type of the node.
  27210. *
  27211. * @type {string}
  27212. * @readonly
  27213. * @static
  27214. */
  27215. static get type() {
  27216. return 'SampleNode';
  27217. }
  27218. /**
  27219. * Creates an instance of SampleNode.
  27220. *
  27221. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  27222. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  27223. */
  27224. constructor( callback, uvNode = null ) {
  27225. super();
  27226. this.callback = callback;
  27227. /**
  27228. * Represents the texture coordinates.
  27229. *
  27230. * @type {?Node<vec2|vec3>}
  27231. * @default null
  27232. */
  27233. this.uvNode = uvNode;
  27234. /**
  27235. * This flag can be used for type testing.
  27236. *
  27237. * @type {boolean}
  27238. * @readonly
  27239. * @default true
  27240. */
  27241. this.isSampleNode = true;
  27242. }
  27243. /**
  27244. * Sets up the node by sampling with the default UV accessor.
  27245. *
  27246. * @returns {Node} The result of the callback function when called with the UV node.
  27247. */
  27248. setup() {
  27249. return this.sample( uv$1() );
  27250. }
  27251. /**
  27252. * Calls the callback function with the provided UV node.
  27253. *
  27254. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  27255. * @returns {Node} The result of the callback function.
  27256. */
  27257. sample( uv ) {
  27258. return this.callback( uv );
  27259. }
  27260. }
  27261. /**
  27262. * Helper function to create a SampleNode wrapped as a node object.
  27263. *
  27264. * @function
  27265. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  27266. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  27267. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  27268. */
  27269. const sample = ( callback, uv = null ) => new SampleNode( callback, nodeObject( uv ) );
  27270. /**
  27271. * This special type of instanced buffer attribute is intended for compute shaders.
  27272. * In earlier three.js versions it was only possible to update attribute data
  27273. * on the CPU via JavaScript and then upload the data to the GPU. With the
  27274. * new material system and renderer it is now possible to use compute shaders
  27275. * to compute the data for an attribute more efficiently on the GPU.
  27276. *
  27277. * The idea is to create an instance of this class and provide it as an input
  27278. * to {@link StorageBufferNode}.
  27279. *
  27280. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  27281. *
  27282. * @augments InstancedBufferAttribute
  27283. */
  27284. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  27285. /**
  27286. * Constructs a new storage instanced buffer attribute.
  27287. *
  27288. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  27289. * The subsequent parameters are then obsolete.
  27290. * @param {number} itemSize - The item size.
  27291. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  27292. */
  27293. constructor( count, itemSize, typeClass = Float32Array ) {
  27294. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  27295. super( array, itemSize );
  27296. /**
  27297. * This flag can be used for type testing.
  27298. *
  27299. * @type {boolean}
  27300. * @readonly
  27301. * @default true
  27302. */
  27303. this.isStorageInstancedBufferAttribute = true;
  27304. }
  27305. }
  27306. /**
  27307. * This special type of buffer attribute is intended for compute shaders.
  27308. * In earlier three.js versions it was only possible to update attribute data
  27309. * on the CPU via JavaScript and then upload the data to the GPU. With the
  27310. * new material system and renderer it is now possible to use compute shaders
  27311. * to compute the data for an attribute more efficiently on the GPU.
  27312. *
  27313. * The idea is to create an instance of this class and provide it as an input
  27314. * to {@link StorageBufferNode}.
  27315. *
  27316. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  27317. *
  27318. * @augments BufferAttribute
  27319. */
  27320. class StorageBufferAttribute extends BufferAttribute {
  27321. /**
  27322. * Constructs a new storage buffer attribute.
  27323. *
  27324. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  27325. * The subsequent parameters are then obsolete.
  27326. * @param {number} itemSize - The item size.
  27327. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  27328. */
  27329. constructor( count, itemSize, typeClass = Float32Array ) {
  27330. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  27331. super( array, itemSize );
  27332. /**
  27333. * This flag can be used for type testing.
  27334. *
  27335. * @type {boolean}
  27336. * @readonly
  27337. * @default true
  27338. */
  27339. this.isStorageBufferAttribute = true;
  27340. }
  27341. }
  27342. /**
  27343. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  27344. *
  27345. * @tsl
  27346. * @function
  27347. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  27348. * @param {string|Struct} [type='float'] - The data type.
  27349. * @returns {StorageBufferNode}
  27350. */
  27351. const attributeArray = ( count, type = 'float' ) => {
  27352. let itemSize, typedArray;
  27353. if ( type.isStructTypeNode === true ) {
  27354. itemSize = type.getLength();
  27355. typedArray = getTypedArrayFromType( 'float' );
  27356. } else {
  27357. itemSize = getLengthFromType( type );
  27358. typedArray = getTypedArrayFromType( type );
  27359. }
  27360. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  27361. const node = storage( buffer, type, count );
  27362. return node;
  27363. };
  27364. /**
  27365. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  27366. *
  27367. * @tsl
  27368. * @function
  27369. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  27370. * @param {string|Struct} [type='float'] - The data type.
  27371. * @returns {StorageBufferNode}
  27372. */
  27373. const instancedArray = ( count, type = 'float' ) => {
  27374. let itemSize, typedArray;
  27375. if ( type.isStructTypeNode === true ) {
  27376. itemSize = type.getLength();
  27377. typedArray = getTypedArrayFromType( 'float' );
  27378. } else {
  27379. itemSize = getLengthFromType( type );
  27380. typedArray = getTypedArrayFromType( type );
  27381. }
  27382. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  27383. const node = storage( buffer, type, buffer.count );
  27384. return node;
  27385. };
  27386. /**
  27387. * A node for representing the uv coordinates of points.
  27388. *
  27389. * Can only be used with a WebGL backend. In WebGPU, point
  27390. * primitives always have the size of one pixel and can thus
  27391. * can't be used as sprite-like objects that display textures.
  27392. *
  27393. * @augments Node
  27394. */
  27395. class PointUVNode extends Node {
  27396. static get type() {
  27397. return 'PointUVNode';
  27398. }
  27399. /**
  27400. * Constructs a new point uv node.
  27401. */
  27402. constructor() {
  27403. super( 'vec2' );
  27404. /**
  27405. * This flag can be used for type testing.
  27406. *
  27407. * @type {boolean}
  27408. * @readonly
  27409. * @default true
  27410. */
  27411. this.isPointUVNode = true;
  27412. }
  27413. generate( /*builder*/ ) {
  27414. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  27415. }
  27416. }
  27417. /**
  27418. * TSL object that represents the uv coordinates of points.
  27419. *
  27420. * @tsl
  27421. * @type {PointUVNode}
  27422. */
  27423. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  27424. const _m1 = /*@__PURE__*/ new Matrix4();
  27425. /**
  27426. * TSL object that represents the scene's background blurriness.
  27427. *
  27428. * @tsl
  27429. * @type {Node<float>}
  27430. */
  27431. const backgroundBlurriness = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( { scene } ) => scene.backgroundBlurriness );
  27432. /**
  27433. * TSL object that represents the scene's background intensity.
  27434. *
  27435. * @tsl
  27436. * @type {Node<float>}
  27437. */
  27438. const backgroundIntensity = /*@__PURE__*/ uniform( 1 ).setGroup( renderGroup ).onRenderUpdate( ( { scene } ) => scene.backgroundIntensity );
  27439. /**
  27440. * TSL object that represents the scene's background rotation.
  27441. *
  27442. * @tsl
  27443. * @type {Node<mat4>}
  27444. */
  27445. const backgroundRotation = /*@__PURE__*/ uniform( new Matrix4() ).setGroup( renderGroup ).onRenderUpdate( ( { scene } ) => {
  27446. const background = scene.background;
  27447. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  27448. // note: since the matrix is orthonormal, we can use the more-efficient transpose() in lieu of invert()
  27449. _m1.makeRotationFromEuler( scene.backgroundRotation ).transpose();
  27450. } else {
  27451. _m1.identity();
  27452. }
  27453. return _m1;
  27454. } );
  27455. /**
  27456. * This special version of a texture node can be used to
  27457. * write data into a storage texture with a compute shader.
  27458. *
  27459. * ```js
  27460. * const storageTexture = new THREE.StorageTexture( width, height );
  27461. *
  27462. * const computeTexture = Fn( ( { storageTexture } ) => {
  27463. *
  27464. * const posX = instanceIndex.mod( width );
  27465. * const posY = instanceIndex.div( width );
  27466. * const indexUV = uvec2( posX, posY );
  27467. *
  27468. * // generate RGB values
  27469. *
  27470. * const r = 1;
  27471. * const g = 1;
  27472. * const b = 1;
  27473. *
  27474. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  27475. *
  27476. * } );
  27477. *
  27478. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  27479. * renderer.computeAsync( computeNode );
  27480. * ```
  27481. *
  27482. * This node can only be used with a WebGPU backend.
  27483. *
  27484. * @augments TextureNode
  27485. */
  27486. class StorageTextureNode extends TextureNode {
  27487. static get type() {
  27488. return 'StorageTextureNode';
  27489. }
  27490. /**
  27491. * Constructs a new storage texture node.
  27492. *
  27493. * @param {StorageTexture} value - The storage texture.
  27494. * @param {Node<vec2|vec3>} uvNode - The uv node.
  27495. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  27496. */
  27497. constructor( value, uvNode, storeNode = null ) {
  27498. super( value, uvNode );
  27499. /**
  27500. * The value node that should be stored in the texture.
  27501. *
  27502. * @type {?Node}
  27503. * @default null
  27504. */
  27505. this.storeNode = storeNode;
  27506. /**
  27507. * The mip level to write to for storage textures.
  27508. *
  27509. * @type {number}
  27510. * @default 0
  27511. */
  27512. this.mipLevel = 0;
  27513. /**
  27514. * This flag can be used for type testing.
  27515. *
  27516. * @type {boolean}
  27517. * @readonly
  27518. * @default true
  27519. */
  27520. this.isStorageTextureNode = true;
  27521. /**
  27522. * The access type of the texture node.
  27523. *
  27524. * @type {string}
  27525. * @default 'writeOnly'
  27526. */
  27527. this.access = NodeAccess.WRITE_ONLY;
  27528. }
  27529. /**
  27530. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  27531. *
  27532. * @param {NodeBuilder} builder - The current node builder.
  27533. * @return {string} The input type.
  27534. */
  27535. getInputType( /*builder*/ ) {
  27536. return 'storageTexture';
  27537. }
  27538. /**
  27539. * Overwrites the default implementation since storage texture
  27540. * coordinates are texel coordinates and should not be transformed
  27541. * by the texture uv matrix.
  27542. *
  27543. * @param {Node} uvNode - The uv node.
  27544. * @return {Node} The unmodified uv node.
  27545. */
  27546. getTransformedUV( uvNode ) {
  27547. return uvNode;
  27548. }
  27549. setup( builder ) {
  27550. super.setup( builder );
  27551. const properties = builder.getNodeProperties( this );
  27552. properties.storeNode = this.storeNode;
  27553. return properties;
  27554. }
  27555. /**
  27556. * Defines the node access.
  27557. *
  27558. * @param {string} value - The node access.
  27559. * @return {StorageTextureNode} A reference to this node.
  27560. */
  27561. setAccess( value ) {
  27562. this.access = value;
  27563. return this;
  27564. }
  27565. /**
  27566. * Sets the mip level to write to.
  27567. *
  27568. * @param {number} level - The mip level.
  27569. * @return {StorageTextureNode} A reference to this node.
  27570. */
  27571. setMipLevel( level ) {
  27572. this.mipLevel = level;
  27573. return this;
  27574. }
  27575. /**
  27576. * Generates the code snippet of the storage node. If no `storeNode`
  27577. * is defined, the texture node is generated as normal texture.
  27578. *
  27579. * @param {NodeBuilder} builder - The current node builder.
  27580. * @param {string} output - The current output.
  27581. * @return {string} The generated code snippet.
  27582. */
  27583. generate( builder, output ) {
  27584. if ( this.storeNode !== null ) {
  27585. this.generateStore( builder );
  27586. return '';
  27587. }
  27588. return super.generate( builder, output );
  27589. }
  27590. /**
  27591. * Generates the snippet for the storage texture.
  27592. *
  27593. * @param {NodeBuilder} builder - The current node builder.
  27594. * @param {string} textureProperty - The texture property.
  27595. * @param {string} uvSnippet - The uv snippet.
  27596. * @param {?string} levelSnippet - The level snippet.
  27597. * @param {?string} biasSnippet - The bias snippet.
  27598. * @param {?string} depthSnippet - The depth snippet.
  27599. * @param {?string} compareSnippet - The compare snippet.
  27600. * @param {?Array<string>} gradSnippet - The grad snippet.
  27601. * @param {?string} offsetSnippet - The offset snippet.
  27602. * @return {string} The generated code snippet.
  27603. */
  27604. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  27605. const texture = this.value;
  27606. return builder.generateStorageTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  27607. }
  27608. /**
  27609. * Convenience method for configuring a read/write node access.
  27610. *
  27611. * @return {StorageTextureNode} A reference to this node.
  27612. */
  27613. toReadWrite() {
  27614. return this.setAccess( NodeAccess.READ_WRITE );
  27615. }
  27616. /**
  27617. * Convenience method for configuring a read-only node access.
  27618. *
  27619. * @return {StorageTextureNode} A reference to this node.
  27620. */
  27621. toReadOnly() {
  27622. return this.setAccess( NodeAccess.READ_ONLY );
  27623. }
  27624. /**
  27625. * Convenience method for configuring a write-only node access.
  27626. *
  27627. * @return {StorageTextureNode} A reference to this node.
  27628. */
  27629. toWriteOnly() {
  27630. return this.setAccess( NodeAccess.WRITE_ONLY );
  27631. }
  27632. /**
  27633. * Stores a value in this storage texture at the given coordinates.
  27634. *
  27635. * @param {Node<vec2|vec3>} uvNode - The storage texture coordinates.
  27636. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  27637. * @return {StorageTextureNode} A storage texture node representing the store operation.
  27638. */
  27639. store( uvNode, storeNode ) {
  27640. const node = this.clone();
  27641. node.referenceNode = this.getBase();
  27642. node.uvNode = uvNode;
  27643. node.storeNode = storeNode;
  27644. if ( storeNode !== null ) node.toStack();
  27645. return node;
  27646. }
  27647. /**
  27648. * Generates the code snippet of the storage texture node.
  27649. *
  27650. * @param {NodeBuilder} builder - The current node builder.
  27651. */
  27652. generateStore( builder ) {
  27653. const properties = builder.getNodeProperties( this );
  27654. const { uvNode, storeNode, depthNode } = properties;
  27655. const textureProperty = super.generate( builder, 'property' );
  27656. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  27657. const storeSnippet = storeNode.build( builder, 'vec4' );
  27658. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  27659. const snippet = builder.generateTextureStore( this.value, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  27660. builder.addLineFlowCode( snippet, this );
  27661. }
  27662. clone() {
  27663. const newNode = super.clone();
  27664. newNode.storeNode = this.storeNode;
  27665. newNode.mipLevel = this.mipLevel;
  27666. newNode.access = this.access;
  27667. return newNode;
  27668. }
  27669. }
  27670. /**
  27671. * TSL function for creating a storage texture node.
  27672. *
  27673. * @tsl
  27674. * @function
  27675. * @param {StorageTexture} value - The storage texture.
  27676. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  27677. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  27678. * @returns {StorageTextureNode}
  27679. */
  27680. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  27681. /**
  27682. * TODO: Explain difference to `storageTexture()`.
  27683. *
  27684. * @tsl
  27685. * @function
  27686. * @param {StorageTexture|StorageTextureNode} value - The storage texture.
  27687. * @param {Node<vec2|vec3>} uvNode - The uv node.
  27688. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  27689. * @returns {StorageTextureNode}
  27690. */
  27691. const textureStore = ( value, uvNode, storeNode ) => {
  27692. let node;
  27693. if ( value.isStorageTextureNode === true ) {
  27694. node = value.store( uvNode, storeNode );
  27695. } else {
  27696. node = storageTexture( value, uvNode, storeNode );
  27697. if ( storeNode !== null ) node.toStack();
  27698. }
  27699. return node;
  27700. };
  27701. /**
  27702. * This special version of a texture node can be used to
  27703. * write data into a 3D storage texture with a compute shader.
  27704. *
  27705. * @augments StorageTextureNode
  27706. */
  27707. class StorageTexture3DNode extends StorageTextureNode {
  27708. static get type() {
  27709. return 'StorageTexture3DNode';
  27710. }
  27711. /**
  27712. * Constructs a new 3D storage texture node.
  27713. *
  27714. * @param {Storage3DTexture} value - The 3D storage texture.
  27715. * @param {Node<vec3>} uvNode - The uv node.
  27716. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  27717. */
  27718. constructor( value, uvNode, storeNode = null ) {
  27719. super( value, uvNode, storeNode );
  27720. /**
  27721. * This flag can be used for type testing.
  27722. *
  27723. * @type {boolean}
  27724. * @readonly
  27725. * @default true
  27726. */
  27727. this.isStorageTexture3DNode = true;
  27728. }
  27729. /**
  27730. * Returns a default uv node which is in context of 3D textures a three-dimensional
  27731. * uv node.
  27732. *
  27733. * @return {Node<vec3>} The default uv node.
  27734. */
  27735. getDefaultUV() {
  27736. return vec3( 0.5, 0.5, 0.5 );
  27737. }
  27738. /**
  27739. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  27740. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  27741. *
  27742. * @param {boolean} value - The update toggle.
  27743. */
  27744. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  27745. /**
  27746. * Generates the uv code snippet.
  27747. *
  27748. * @param {NodeBuilder} builder - The current node builder.
  27749. * @param {Node} uvNode - The uv node to generate code for.
  27750. * @return {string} The generated code snippet.
  27751. */
  27752. generateUV( builder, uvNode ) {
  27753. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  27754. }
  27755. /**
  27756. * Generates the offset code snippet.
  27757. *
  27758. * @param {NodeBuilder} builder - The current node builder.
  27759. * @param {Node} offsetNode - The offset node to generate code for.
  27760. * @return {string} The generated code snippet.
  27761. */
  27762. generateOffset( builder, offsetNode ) {
  27763. return offsetNode.build( builder, 'ivec3' );
  27764. }
  27765. }
  27766. /**
  27767. * TSL function for creating a 3D storage texture node.
  27768. *
  27769. * @tsl
  27770. * @function
  27771. * @param {Storage3DTexture} value - The 3D storage texture.
  27772. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  27773. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  27774. * @returns {StorageTexture3DNode}
  27775. */
  27776. const storageTexture3D = /*@__PURE__*/ nodeProxy( StorageTexture3DNode ).setParameterLength( 1, 3 );
  27777. const normal = Fn( ( { texture, uv } ) => {
  27778. const epsilon = 0.0001;
  27779. const ret = vec3().toVar();
  27780. If( uv.x.lessThan( epsilon ), () => {
  27781. ret.assign( vec3( 1, 0, 0 ) );
  27782. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  27783. ret.assign( vec3( 0, 1, 0 ) );
  27784. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  27785. ret.assign( vec3( 0, 0, 1 ) );
  27786. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  27787. ret.assign( vec3( -1, 0, 0 ) );
  27788. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  27789. ret.assign( vec3( 0, -1, 0 ) );
  27790. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  27791. ret.assign( vec3( 0, 0, -1 ) );
  27792. } ).Else( () => {
  27793. const step = 0.01;
  27794. 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 );
  27795. 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 );
  27796. 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 );
  27797. ret.assign( vec3( x, y, z ) );
  27798. } );
  27799. return ret.normalize();
  27800. } );
  27801. /**
  27802. * This type of uniform node represents a 3D texture.
  27803. *
  27804. * @augments TextureNode
  27805. */
  27806. class Texture3DNode extends TextureNode {
  27807. static get type() {
  27808. return 'Texture3DNode';
  27809. }
  27810. /**
  27811. * Constructs a new 3D texture node.
  27812. *
  27813. * @param {Data3DTexture} value - The 3D texture.
  27814. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  27815. * @param {?Node<int>} [levelNode=null] - The level node.
  27816. */
  27817. constructor( value, uvNode = null, levelNode = null ) {
  27818. super( value, uvNode, levelNode );
  27819. /**
  27820. * This flag can be used for type testing.
  27821. *
  27822. * @type {boolean}
  27823. * @readonly
  27824. * @default true
  27825. */
  27826. this.isTexture3DNode = true;
  27827. }
  27828. /**
  27829. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  27830. *
  27831. * @param {NodeBuilder} builder - The current node builder.
  27832. * @return {string} The input type.
  27833. */
  27834. getInputType( /*builder*/ ) {
  27835. return 'texture3D';
  27836. }
  27837. /**
  27838. * Returns a default uv node which is in context of 3D textures a three-dimensional
  27839. * uv node.
  27840. *
  27841. * @return {Node<vec3>} The default uv node.
  27842. */
  27843. getDefaultUV() {
  27844. return vec3( 0.5, 0.5, 0.5 );
  27845. }
  27846. /**
  27847. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  27848. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  27849. *
  27850. * @param {boolean} value - The update toggle.
  27851. */
  27852. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  27853. /**
  27854. * Generates the uv code snippet.
  27855. *
  27856. * @param {NodeBuilder} builder - The current node builder.
  27857. * @param {Node} uvNode - The uv node to generate code for.
  27858. * @return {string} The generated code snippet.
  27859. */
  27860. generateUV( builder, uvNode ) {
  27861. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  27862. }
  27863. /**
  27864. * Generates the offset code snippet.
  27865. *
  27866. * @param {NodeBuilder} builder - The current node builder.
  27867. * @param {Node} offsetNode - The offset node to generate code for.
  27868. * @return {string} The generated code snippet.
  27869. */
  27870. generateOffset( builder, offsetNode ) {
  27871. return offsetNode.build( builder, 'ivec3' );
  27872. }
  27873. /**
  27874. * Computes the normal for the given uv. These texture coordiantes represent a
  27875. * position inside the 3D texture. Unlike geometric normals, this normal
  27876. * represents a slope or gradient of scalar data inside the 3D texture.
  27877. *
  27878. * @param {Node<vec3>} uvNode - The uv node that defines a position in the 3D texture.
  27879. * @return {Node<vec3>} The normal representing the slope/gradient in the data.
  27880. */
  27881. normal( uvNode ) {
  27882. return normal( { texture: this, uv: uvNode } );
  27883. }
  27884. }
  27885. /**
  27886. * TSL function for creating a 3D texture node.
  27887. *
  27888. * @tsl
  27889. * @function
  27890. * @param {Data3DTexture} value - The 3D texture.
  27891. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  27892. * @param {?Node<int>} [levelNode=null] - The level node.
  27893. * @returns {Texture3DNode}
  27894. */
  27895. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  27896. /**
  27897. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  27898. *
  27899. * @tsl
  27900. * @function
  27901. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  27902. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  27903. * @param {?Node<int>} [levelNode=null] - The level node.
  27904. * @param {?Node<float>} [biasNode=null] - The bias node.
  27905. * @returns {TextureNode}
  27906. */
  27907. const texture3DLoad = ( ...params ) => texture3D( ...params ).setSampler( false );
  27908. /**
  27909. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  27910. *
  27911. * @tsl
  27912. * @function
  27913. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  27914. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  27915. * @param {?Node<int>} [levelNode=null] - The level node.
  27916. * @returns {TextureNode}
  27917. */
  27918. const texture3DLevel = ( value, uvNode, levelNode ) => texture3D( value, uvNode ).level( levelNode );
  27919. /**
  27920. * A special type of reference node that allows to link values in
  27921. * `userData` fields to node objects.
  27922. * ```js
  27923. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  27924. *
  27925. * const material = new THREE.SpriteNodeMaterial();
  27926. * material.rotationNode = userData( 'rotation', 'float' );
  27927. * ```
  27928. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  27929. * will automatically be updated when the `rotation` user data field changes.
  27930. *
  27931. * @augments ReferenceNode
  27932. */
  27933. class UserDataNode extends ReferenceNode {
  27934. static get type() {
  27935. return 'UserDataNode';
  27936. }
  27937. /**
  27938. * Constructs a new user data node.
  27939. *
  27940. * @param {string} property - The property name that should be referenced by the node.
  27941. * @param {string} inputType - The node data type of the reference.
  27942. * @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.
  27943. */
  27944. constructor( property, inputType, userData = null ) {
  27945. super( property, inputType, userData );
  27946. /**
  27947. * A reference to the `userData` object. If not provided, the `userData`
  27948. * property of the 3D object that uses the node material is evaluated.
  27949. *
  27950. * @type {?Object}
  27951. * @default null
  27952. */
  27953. this.userData = userData;
  27954. }
  27955. /**
  27956. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  27957. * `userData` field.
  27958. *
  27959. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  27960. * @return {Object} A reference to the `userData` field.
  27961. */
  27962. updateReference( state ) {
  27963. this.reference = this.userData !== null ? this.userData : state.object.userData;
  27964. return this.reference;
  27965. }
  27966. }
  27967. /**
  27968. * TSL function for creating a user data node.
  27969. *
  27970. * @tsl
  27971. * @function
  27972. * @param {string} name - The property name that should be referenced by the node.
  27973. * @param {string} inputType - The node data type of the reference.
  27974. * @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.
  27975. * @returns {UserDataNode}
  27976. */
  27977. const userData = ( name, inputType, userData ) => new UserDataNode( name, inputType, userData );
  27978. const _objectData = new WeakMap();
  27979. /**
  27980. * A node for representing motion or velocity vectors. Foundation
  27981. * for advanced post processing effects like motion blur or TRAA.
  27982. *
  27983. * The node keeps track of the model, view and projection matrices
  27984. * of the previous frame and uses them to compute offsets in NDC space.
  27985. * These offsets represent the final velocity.
  27986. *
  27987. * @augments TempNode
  27988. */
  27989. class VelocityNode extends TempNode {
  27990. static get type() {
  27991. return 'VelocityNode';
  27992. }
  27993. /**
  27994. * Constructs a new vertex color node.
  27995. */
  27996. constructor() {
  27997. super( 'vec2' );
  27998. /**
  27999. * The current projection matrix.
  28000. *
  28001. * @type {?Matrix4}
  28002. * @default null
  28003. */
  28004. this.projectionMatrix = null;
  28005. /**
  28006. * Overwritten since velocity nodes are updated per object.
  28007. *
  28008. * @type {string}
  28009. * @default 'object'
  28010. */
  28011. this.updateType = NodeUpdateType.OBJECT;
  28012. /**
  28013. * Overwritten since velocity nodes save data after the update.
  28014. *
  28015. * @type {string}
  28016. * @default 'object'
  28017. */
  28018. this.updateAfterType = NodeUpdateType.OBJECT;
  28019. /**
  28020. * Uniform node representing the previous model matrix in world space.
  28021. *
  28022. * @type {UniformNode<mat4>}
  28023. * @default null
  28024. */
  28025. this.previousModelWorldMatrix = uniform( new Matrix4() );
  28026. /**
  28027. * Uniform node representing the previous projection matrix.
  28028. *
  28029. * @type {UniformNode<mat4>}
  28030. * @default null
  28031. */
  28032. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  28033. /**
  28034. * Uniform node representing the previous view matrix.
  28035. *
  28036. * @type {UniformNode<mat4>}
  28037. * @default null
  28038. */
  28039. this.previousCameraViewMatrix = uniform( new Matrix4() );
  28040. }
  28041. /**
  28042. * Sets the given projection matrix.
  28043. *
  28044. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  28045. */
  28046. setProjectionMatrix( projectionMatrix ) {
  28047. this.projectionMatrix = projectionMatrix;
  28048. }
  28049. /**
  28050. * Updates velocity specific uniforms.
  28051. *
  28052. * @param {NodeFrame} frame - A reference to the current node frame.
  28053. */
  28054. update( { frameId, camera, object } ) {
  28055. const previousModelMatrix = getPreviousMatrix( object );
  28056. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  28057. //
  28058. const cameraData = getData( camera );
  28059. if ( cameraData.frameId !== frameId ) {
  28060. cameraData.frameId = frameId;
  28061. if ( cameraData.previousProjectionMatrix === undefined ) {
  28062. cameraData.previousProjectionMatrix = new Matrix4();
  28063. cameraData.previousCameraViewMatrix = new Matrix4();
  28064. cameraData.currentProjectionMatrix = new Matrix4();
  28065. cameraData.currentCameraViewMatrix = new Matrix4();
  28066. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  28067. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  28068. } else {
  28069. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  28070. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  28071. }
  28072. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  28073. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  28074. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  28075. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  28076. }
  28077. }
  28078. /**
  28079. * Overwritten to updated velocity specific uniforms.
  28080. *
  28081. * @param {NodeFrame} frame - A reference to the current node frame.
  28082. */
  28083. updateAfter( { object } ) {
  28084. getPreviousMatrix( object ).copy( object.matrixWorld );
  28085. }
  28086. /**
  28087. * Implements the velocity computation based on the previous and current vertex data.
  28088. *
  28089. * @param {NodeBuilder} builder - A reference to the current node builder.
  28090. * @return {Node<vec2>} The motion vector.
  28091. */
  28092. setup( /*builder*/ ) {
  28093. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  28094. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  28095. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  28096. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  28097. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  28098. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  28099. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  28100. return velocity;
  28101. }
  28102. }
  28103. function getData( object ) {
  28104. let objectData = _objectData.get( object );
  28105. if ( objectData === undefined ) {
  28106. objectData = {};
  28107. _objectData.set( object, objectData );
  28108. }
  28109. return objectData;
  28110. }
  28111. function getPreviousMatrix( object, index = 0 ) {
  28112. const objectData = getData( object );
  28113. let matrix = objectData[ index ];
  28114. if ( matrix === undefined ) {
  28115. objectData[ index ] = matrix = new Matrix4();
  28116. objectData[ index ].copy( object.matrixWorld );
  28117. }
  28118. return matrix;
  28119. }
  28120. /**
  28121. * TSL object that represents the velocity of a render pass.
  28122. *
  28123. * @tsl
  28124. * @type {VelocityNode}
  28125. */
  28126. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  28127. /**
  28128. * Represents a "Color Burn" blend mode.
  28129. *
  28130. * It's designed to darken the base layer's colors based on the color of the blend layer.
  28131. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  28132. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  28133. *
  28134. * @tsl
  28135. * @function
  28136. * @param {Node<vec3>} base - The base color.
  28137. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  28138. * @return {Node<vec3>} The result.
  28139. */
  28140. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  28141. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  28142. } ).setLayout( {
  28143. name: 'blendBurn',
  28144. type: 'vec3',
  28145. inputs: [
  28146. { name: 'base', type: 'vec3' },
  28147. { name: 'blend', type: 'vec3' }
  28148. ]
  28149. } );
  28150. /**
  28151. * Represents a "Color Dodge" blend mode.
  28152. *
  28153. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  28154. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  28155. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  28156. *
  28157. * @tsl
  28158. * @function
  28159. * @param {Node<vec3>} base - The base color.
  28160. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  28161. * @return {Node<vec3>} The result.
  28162. */
  28163. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  28164. return min$1( base.div( blend.oneMinus() ), 1.0 );
  28165. } ).setLayout( {
  28166. name: 'blendDodge',
  28167. type: 'vec3',
  28168. inputs: [
  28169. { name: 'base', type: 'vec3' },
  28170. { name: 'blend', type: 'vec3' }
  28171. ]
  28172. } );
  28173. /**
  28174. * Represents a "Screen" blend mode.
  28175. *
  28176. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  28177. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  28178. * effects.
  28179. *
  28180. * @tsl
  28181. * @function
  28182. * @param {Node<vec3>} base - The base color.
  28183. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  28184. * @return {Node<vec3>} The result.
  28185. */
  28186. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  28187. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  28188. } ).setLayout( {
  28189. name: 'blendScreen',
  28190. type: 'vec3',
  28191. inputs: [
  28192. { name: 'base', type: 'vec3' },
  28193. { name: 'blend', type: 'vec3' }
  28194. ]
  28195. } );
  28196. /**
  28197. * Represents a "Overlay" blend mode.
  28198. *
  28199. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  28200. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  28201. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  28202. *
  28203. * @tsl
  28204. * @function
  28205. * @param {Node<vec3>} base - The base color.
  28206. * @param {Node<vec3>} blend - The blend color
  28207. * @return {Node<vec3>} The result.
  28208. */
  28209. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  28210. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  28211. } ).setLayout( {
  28212. name: 'blendOverlay',
  28213. type: 'vec3',
  28214. inputs: [
  28215. { name: 'base', type: 'vec3' },
  28216. { name: 'blend', type: 'vec3' }
  28217. ]
  28218. } );
  28219. /**
  28220. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  28221. * It assumes both input colors have non-premultiplied alpha.
  28222. *
  28223. * @tsl
  28224. * @function
  28225. * @param {Node<vec4>} base - The base color.
  28226. * @param {Node<vec4>} blend - The blend color
  28227. * @return {Node<vec4>} The result.
  28228. */
  28229. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  28230. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  28231. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  28232. } ).setLayout( {
  28233. name: 'blendColor',
  28234. type: 'vec4',
  28235. inputs: [
  28236. { name: 'base', type: 'vec4' },
  28237. { name: 'blend', type: 'vec4' }
  28238. ]
  28239. } );
  28240. /**
  28241. * Computes a grayscale value for the given RGB color value.
  28242. *
  28243. * @tsl
  28244. * @function
  28245. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  28246. * @return {Node<vec3>} The grayscale color.
  28247. */
  28248. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  28249. return luminance( color.rgb );
  28250. } );
  28251. /**
  28252. * Super-saturates or desaturates the given RGB color.
  28253. *
  28254. * @tsl
  28255. * @function
  28256. * @param {Node<vec3>} color - The input color.
  28257. * @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.
  28258. * @return {Node<vec3>} The saturated color.
  28259. */
  28260. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  28261. return adjustment.mix( luminance( color.rgb ), color.rgb );
  28262. } );
  28263. /**
  28264. * Selectively enhance the intensity of less saturated RGB colors. Can result
  28265. * in a more natural and visually appealing image with enhanced color depth
  28266. * compared to {@link ColorAdjustment#saturation}.
  28267. *
  28268. * @tsl
  28269. * @function
  28270. * @param {Node<vec3>} color - The input color.
  28271. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  28272. * @return {Node<vec3>} The updated color.
  28273. */
  28274. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  28275. const average = add( color.r, color.g, color.b ).div( 3.0 );
  28276. const mx = color.r.max( color.g.max( color.b ) );
  28277. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  28278. return mix( color.rgb, mx, amt );
  28279. } );
  28280. /**
  28281. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  28282. *
  28283. * @tsl
  28284. * @function
  28285. * @param {Node<vec3>} color - The input color.
  28286. * @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.
  28287. * @return {Node<vec3>} The updated color.
  28288. */
  28289. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  28290. const k = vec3( 0.57735, 0.57735, 0.57735 );
  28291. const cosAngle = adjustment.cos();
  28292. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  28293. } );
  28294. /**
  28295. * Computes the luminance for the given RGB color value.
  28296. *
  28297. * @tsl
  28298. * @function
  28299. * @param {Node<vec3>} color - The color value to compute the luminance for.
  28300. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  28301. * @return {Node<float>} The luminance.
  28302. */
  28303. const luminance = (
  28304. color,
  28305. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  28306. ) => dot( color, luminanceCoefficients );
  28307. /**
  28308. * Color Decision List (CDL) v1.2
  28309. *
  28310. * Compact representation of color grading information, defined by slope, offset, power, and
  28311. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  28312. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  28313. *
  28314. * @tsl
  28315. * @function
  28316. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  28317. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  28318. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  28319. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  28320. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  28321. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  28322. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  28323. *
  28324. * References:
  28325. * - ASC CDL v1.2
  28326. * - {@link https://blender.stackexchange.com/a/55239/43930}
  28327. * - {@link https://docs.acescentral.com/specifications/acescc/}
  28328. */
  28329. const cdl = /*@__PURE__*/ Fn( ( [
  28330. color,
  28331. slope = vec3( 1 ),
  28332. offset = vec3( 0 ),
  28333. power = vec3( 1 ),
  28334. saturation = float( 1 ),
  28335. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  28336. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  28337. ] ) => {
  28338. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  28339. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  28340. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  28341. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  28342. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  28343. const pv = v.pow( power ).toVar();
  28344. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  28345. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  28346. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  28347. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  28348. return vec4( v.rgb, color.a );
  28349. } );
  28350. /**
  28351. * TSL function for creating a posterize effect which reduces the number of colors
  28352. * in an image, resulting in a more blocky and stylized appearance.
  28353. *
  28354. * @tsl
  28355. * @function
  28356. * @param {Node} sourceNode - The input color.
  28357. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  28358. * @returns {Node} The posterized color.
  28359. */
  28360. const posterize = Fn( ( [ source, steps ] ) => {
  28361. return source.mul( steps ).floor().div( steps );
  28362. } );
  28363. let _sharedFramebuffer = null;
  28364. /**
  28365. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  28366. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  28367. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  28368. *
  28369. * @augments ViewportTextureNode
  28370. */
  28371. class ViewportSharedTextureNode extends ViewportTextureNode {
  28372. static get type() {
  28373. return 'ViewportSharedTextureNode';
  28374. }
  28375. /**
  28376. * Constructs a new viewport shared texture node.
  28377. *
  28378. * @param {Node} [uvNode=screenUV] - The uv node.
  28379. * @param {?Node} [levelNode=null] - The level node.
  28380. */
  28381. constructor( uvNode = screenUV, levelNode = null ) {
  28382. if ( _sharedFramebuffer === null ) {
  28383. _sharedFramebuffer = new FramebufferTexture();
  28384. }
  28385. super( uvNode, levelNode, _sharedFramebuffer );
  28386. }
  28387. /**
  28388. * Overwritten so the method always returns the unique shared
  28389. * framebuffer texture.
  28390. *
  28391. * @return {FramebufferTexture} The shared framebuffer texture.
  28392. */
  28393. getTextureForReference() {
  28394. return _sharedFramebuffer;
  28395. }
  28396. updateReference() {
  28397. return this;
  28398. }
  28399. }
  28400. /**
  28401. * TSL function for creating a shared viewport texture node.
  28402. *
  28403. * @tsl
  28404. * @function
  28405. * @param {?Node} [uvNode=screenUV] - The uv node.
  28406. * @param {?Node} [levelNode=null] - The level node.
  28407. * @returns {ViewportSharedTextureNode}
  28408. */
  28409. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  28410. const _size = /*@__PURE__*/ new Vector2();
  28411. /**
  28412. * Represents the texture of a pass node.
  28413. *
  28414. * @augments TextureNode
  28415. */
  28416. class PassTextureNode extends TextureNode {
  28417. static get type() {
  28418. return 'PassTextureNode';
  28419. }
  28420. /**
  28421. * Constructs a new pass texture node.
  28422. *
  28423. * @param {PassNode} passNode - The pass node.
  28424. * @param {Texture} texture - The output texture.
  28425. */
  28426. constructor( passNode, texture ) {
  28427. super( texture );
  28428. /**
  28429. * A reference to the pass node.
  28430. *
  28431. * @type {PassNode}
  28432. */
  28433. this.passNode = passNode;
  28434. /**
  28435. * This flag can be used for type testing.
  28436. *
  28437. * @type {boolean}
  28438. * @default true
  28439. * @readonly
  28440. */
  28441. this.isPassTextureNode = true;
  28442. this.setUpdateMatrix( false );
  28443. }
  28444. setup( builder ) {
  28445. const properties = builder.getNodeProperties( this );
  28446. properties.passNode = this.passNode;
  28447. return super.setup( builder );
  28448. }
  28449. clone() {
  28450. return new this.constructor( this.passNode, this.value );
  28451. }
  28452. }
  28453. /**
  28454. * An extension of `PassTextureNode` which allows to manage more than one
  28455. * internal texture. Relevant for the `getPreviousTexture()` related API.
  28456. *
  28457. * @augments PassTextureNode
  28458. */
  28459. class PassMultipleTextureNode extends PassTextureNode {
  28460. static get type() {
  28461. return 'PassMultipleTextureNode';
  28462. }
  28463. /**
  28464. * Constructs a new pass texture node.
  28465. *
  28466. * @param {PassNode} passNode - The pass node.
  28467. * @param {string} textureName - The output texture name.
  28468. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  28469. */
  28470. constructor( passNode, textureName, previousTexture = false ) {
  28471. // null is passed to the super call since this class does not
  28472. // use an external texture for rendering pass data into. Instead
  28473. // the texture is managed by the pass node itself
  28474. super( passNode, null );
  28475. /**
  28476. * The output texture name.
  28477. *
  28478. * @type {string}
  28479. */
  28480. this.textureName = textureName;
  28481. /**
  28482. * Whether previous frame data should be used or not.
  28483. *
  28484. * @type {boolean}
  28485. */
  28486. this.previousTexture = previousTexture;
  28487. /**
  28488. * This flag can be used for type testing.
  28489. *
  28490. * @type {boolean}
  28491. * @default true
  28492. * @readonly
  28493. */
  28494. this.isPassMultipleTextureNode = true;
  28495. }
  28496. /**
  28497. * Updates the texture reference of this node.
  28498. */
  28499. updateTexture() {
  28500. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  28501. }
  28502. setup( builder ) {
  28503. this.updateTexture();
  28504. return super.setup( builder );
  28505. }
  28506. clone() {
  28507. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  28508. newNode.uvNode = this.uvNode;
  28509. newNode.levelNode = this.levelNode;
  28510. newNode.biasNode = this.biasNode;
  28511. newNode.sampler = this.sampler;
  28512. newNode.depthNode = this.depthNode;
  28513. newNode.compareNode = this.compareNode;
  28514. newNode.gradNode = this.gradNode;
  28515. newNode.gatherNode = this.gatherNode;
  28516. newNode.offsetNode = this.offsetNode;
  28517. return newNode;
  28518. }
  28519. }
  28520. /**
  28521. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  28522. * This pass produces a render for the given scene and camera and can provide multiple outputs
  28523. * via MRT for further processing.
  28524. *
  28525. * ```js
  28526. * const postProcessing = new RenderPipeline( renderer );
  28527. *
  28528. * const scenePass = pass( scene, camera );
  28529. *
  28530. * postProcessing.outputNode = scenePass;
  28531. * ```
  28532. *
  28533. * @augments TempNode
  28534. */
  28535. class PassNode extends TempNode {
  28536. static get type() {
  28537. return 'PassNode';
  28538. }
  28539. /**
  28540. * Constructs a new pass node.
  28541. *
  28542. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  28543. * @param {Scene} scene - A reference to the scene.
  28544. * @param {Camera} camera - A reference to the camera.
  28545. * @param {Object} options - Options for the internal render target.
  28546. */
  28547. constructor( scope, scene, camera, options = {} ) {
  28548. super( 'vec4' );
  28549. /**
  28550. * The scope of the pass. The scope determines whether the node outputs color or depth.
  28551. *
  28552. * @type {('color'|'depth')}
  28553. */
  28554. this.scope = scope;
  28555. /**
  28556. * A reference to the scene.
  28557. *
  28558. * @type {Scene}
  28559. */
  28560. this.scene = scene;
  28561. /**
  28562. * A reference to the camera.
  28563. *
  28564. * @type {Camera}
  28565. */
  28566. this.camera = camera;
  28567. /**
  28568. * Options for the internal render target.
  28569. *
  28570. * @type {Object}
  28571. */
  28572. this.options = options;
  28573. /**
  28574. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  28575. * @private
  28576. * @type {number}
  28577. * @default 1
  28578. */
  28579. this._width = 1;
  28580. /**
  28581. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  28582. * @private
  28583. * @type {number}
  28584. * @default 1
  28585. */
  28586. this._height = 1;
  28587. const renderTarget = new RenderTarget( this._width, this._height, { type: HalfFloatType, ...options, } );
  28588. renderTarget.texture.name = 'output';
  28589. let depthTexture = null;
  28590. if ( this.scope === PassNode.DEPTH || options.depthBuffer !== false ) {
  28591. depthTexture = new DepthTexture();
  28592. depthTexture.isRenderTargetTexture = true;
  28593. //depthTexture.type = FloatType;
  28594. depthTexture.name = 'depth';
  28595. renderTarget.depthTexture = depthTexture;
  28596. }
  28597. /**
  28598. * The pass's render target.
  28599. *
  28600. * @type {RenderTarget}
  28601. */
  28602. this.renderTarget = renderTarget;
  28603. /**
  28604. * An optional override material for the pass.
  28605. *
  28606. * @type {Material|null}
  28607. */
  28608. this.overrideMaterial = null;
  28609. /**
  28610. * Whether the pass is transparent.
  28611. *
  28612. * @type {boolean}
  28613. * @default false
  28614. */
  28615. this.transparent = true;
  28616. /**
  28617. * Whether the pass is opaque.
  28618. *
  28619. * @type {boolean}
  28620. * @default true
  28621. */
  28622. this.opaque = true;
  28623. /**
  28624. * An optional global context for the pass.
  28625. *
  28626. * @type {ContextNode|null}
  28627. */
  28628. this.contextNode = null;
  28629. /**
  28630. * A cache for the context node.
  28631. *
  28632. * @private
  28633. * @type {?Object}
  28634. * @default null
  28635. */
  28636. this._contextNodeCache = null;
  28637. /**
  28638. * A dictionary holding the internal result textures.
  28639. *
  28640. * @private
  28641. * @type {{ output: Texture, depth: ?DepthTexture }}
  28642. */
  28643. this._textures = {
  28644. output: renderTarget.texture
  28645. };
  28646. if ( depthTexture !== null ) {
  28647. this._textures.depth = depthTexture;
  28648. }
  28649. /**
  28650. * A dictionary holding the internal texture nodes.
  28651. *
  28652. * @private
  28653. * @type {Object<string, TextureNode>}
  28654. */
  28655. this._textureNodes = {};
  28656. /**
  28657. * A dictionary holding the internal depth nodes.
  28658. *
  28659. * @private
  28660. * @type {Object}
  28661. */
  28662. this._linearDepthNodes = {};
  28663. /**
  28664. * A dictionary holding the internal viewZ nodes.
  28665. *
  28666. * @private
  28667. * @type {Object}
  28668. */
  28669. this._viewZNodes = {};
  28670. /**
  28671. * A dictionary holding the texture data of the previous frame.
  28672. * Used for computing velocity/motion vectors.
  28673. *
  28674. * @private
  28675. * @type {Object<string, Texture>}
  28676. */
  28677. this._previousTextures = {};
  28678. /**
  28679. * A dictionary holding the texture nodes of the previous frame.
  28680. * Used for computing velocity/motion vectors.
  28681. *
  28682. * @private
  28683. * @type {Object<string, TextureNode>}
  28684. */
  28685. this._previousTextureNodes = {};
  28686. /**
  28687. * The `near` property of the camera as a uniform.
  28688. *
  28689. * @private
  28690. * @type {UniformNode}
  28691. */
  28692. this._cameraNear = uniform( 0 );
  28693. /**
  28694. * The `far` property of the camera as a uniform.
  28695. *
  28696. * @private
  28697. * @type {UniformNode}
  28698. */
  28699. this._cameraFar = uniform( 0 );
  28700. /**
  28701. * A MRT node configuring the MRT settings.
  28702. *
  28703. * @private
  28704. * @type {?MRTNode}
  28705. * @default null
  28706. */
  28707. this._mrt = null;
  28708. /**
  28709. * Layer object for configuring the camera that is used
  28710. * to produce the pass.
  28711. *
  28712. * @private
  28713. * @type {?Layers}
  28714. * @default null
  28715. */
  28716. this._layers = null;
  28717. /**
  28718. * Scales the resolution of the internal render target.
  28719. *
  28720. * @private
  28721. * @type {number}
  28722. * @default 1
  28723. */
  28724. this._resolutionScale = 1;
  28725. /**
  28726. * Custom viewport definition.
  28727. *
  28728. * @private
  28729. * @type {?Vector4}
  28730. * @default null
  28731. */
  28732. this._viewport = null;
  28733. /**
  28734. * Custom scissor definition.
  28735. *
  28736. * @private
  28737. * @type {?Vector4}
  28738. * @default null
  28739. */
  28740. this._scissor = null;
  28741. /**
  28742. * This flag can be used for type testing.
  28743. *
  28744. * @type {boolean}
  28745. * @readonly
  28746. * @default true
  28747. */
  28748. this.isPassNode = true;
  28749. /**
  28750. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  28751. * scene once per frame in its {@link PassNode#updateBefore} method.
  28752. *
  28753. * @type {string}
  28754. * @default 'frame'
  28755. */
  28756. this.updateBeforeType = NodeUpdateType.FRAME;
  28757. /**
  28758. * This flag is used for global cache.
  28759. *
  28760. * @type {boolean}
  28761. * @default true
  28762. */
  28763. this.global = true;
  28764. }
  28765. /**
  28766. * Sets the resolution scale for the pass.
  28767. * The resolution scale is a factor that is multiplied with the renderer's width and height.
  28768. *
  28769. * @param {number} resolutionScale - The resolution scale to set. A value of `1` means full resolution.
  28770. * @return {PassNode} A reference to this pass.
  28771. */
  28772. setResolutionScale( resolutionScale ) {
  28773. this._resolutionScale = resolutionScale;
  28774. return this;
  28775. }
  28776. /**
  28777. * Gets the current resolution scale of the pass.
  28778. *
  28779. * @return {number} The current resolution scale. A value of `1` means full resolution.
  28780. */
  28781. getResolutionScale() {
  28782. return this._resolutionScale;
  28783. }
  28784. /**
  28785. * Sets the resolution for the pass.
  28786. * The resolution is a factor that is multiplied with the renderer's width and height.
  28787. *
  28788. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  28789. * @return {PassNode} A reference to this pass.
  28790. * @deprecated since r181. Use {@link PassNode#setResolutionScale `setResolutionScale()`} instead.
  28791. */
  28792. setResolution( resolution ) { // @deprecated, r181
  28793. warn( 'PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead.' );
  28794. return this.setResolutionScale( resolution );
  28795. }
  28796. /**
  28797. * Gets the current resolution of the pass.
  28798. *
  28799. * @return {number} The current resolution. A value of `1` means full resolution.
  28800. * @deprecated since r181. Use {@link PassNode#getResolutionScale `getResolutionScale()`} instead.
  28801. */
  28802. getResolution() { // @deprecated, r181
  28803. warn( 'PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead.' );
  28804. return this.getResolutionScale();
  28805. }
  28806. /**
  28807. * Sets the layer configuration that should be used when rendering the pass.
  28808. *
  28809. * @param {Layers} layers - The layers object to set.
  28810. * @return {PassNode} A reference to this pass.
  28811. */
  28812. setLayers( layers ) {
  28813. this._layers = layers;
  28814. return this;
  28815. }
  28816. /**
  28817. * Gets the current layer configuration of the pass.
  28818. *
  28819. * @return {?Layers} .
  28820. */
  28821. getLayers() {
  28822. return this._layers;
  28823. }
  28824. /**
  28825. * Sets the given MRT node to setup MRT for this pass.
  28826. *
  28827. * @param {MRTNode} mrt - The MRT object.
  28828. * @return {PassNode} A reference to this pass.
  28829. */
  28830. setMRT( mrt ) {
  28831. this._mrt = mrt;
  28832. return this;
  28833. }
  28834. /**
  28835. * Returns the current MRT node.
  28836. *
  28837. * @return {MRTNode} The current MRT node.
  28838. */
  28839. getMRT() {
  28840. return this._mrt;
  28841. }
  28842. /**
  28843. * Returns the texture for the given output name.
  28844. *
  28845. * @param {string} name - The output name to get the texture for.
  28846. * @return {Texture} The texture.
  28847. */
  28848. getTexture( name ) {
  28849. let texture = this._textures[ name ];
  28850. if ( texture === undefined ) {
  28851. if ( name === 'depth' ) {
  28852. throw new Error( 'THREE.PassNode: Depth texture is not available for this pass.' );
  28853. }
  28854. const refTexture = this.renderTarget.texture;
  28855. texture = refTexture.clone();
  28856. texture.name = name;
  28857. this._textures[ name ] = texture;
  28858. this.renderTarget.textures.push( texture );
  28859. }
  28860. return texture;
  28861. }
  28862. /**
  28863. * Returns the texture holding the data of the previous frame for the given output name.
  28864. *
  28865. * @param {string} name - The output name to get the texture for.
  28866. * @return {Texture} The texture holding the data of the previous frame.
  28867. */
  28868. getPreviousTexture( name ) {
  28869. let texture = this._previousTextures[ name ];
  28870. if ( texture === undefined ) {
  28871. texture = this.getTexture( name ).clone();
  28872. this._previousTextures[ name ] = texture;
  28873. }
  28874. return texture;
  28875. }
  28876. /**
  28877. * Switches current and previous textures for the given output name.
  28878. *
  28879. * @param {string} name - The output name.
  28880. */
  28881. toggleTexture( name ) {
  28882. const prevTexture = this._previousTextures[ name ];
  28883. if ( prevTexture !== undefined ) {
  28884. const texture = this._textures[ name ];
  28885. const index = this.renderTarget.textures.indexOf( texture );
  28886. this.renderTarget.textures[ index ] = prevTexture;
  28887. this._textures[ name ] = prevTexture;
  28888. this._previousTextures[ name ] = texture;
  28889. this._textureNodes[ name ].updateTexture();
  28890. this._previousTextureNodes[ name ].updateTexture();
  28891. }
  28892. }
  28893. /**
  28894. * Returns the texture node for the given output name.
  28895. *
  28896. * @param {string} [name='output'] - The output name to get the texture node for.
  28897. * @return {TextureNode} The texture node.
  28898. */
  28899. getTextureNode( name = 'output' ) {
  28900. let textureNode = this._textureNodes[ name ];
  28901. if ( textureNode === undefined ) {
  28902. textureNode = new PassMultipleTextureNode( this, name );
  28903. textureNode.updateTexture();
  28904. this._textureNodes[ name ] = textureNode;
  28905. }
  28906. return textureNode;
  28907. }
  28908. /**
  28909. * Returns the previous texture node for the given output name.
  28910. *
  28911. * @param {string} [name='output'] - The output name to get the previous texture node for.
  28912. * @return {TextureNode} The previous texture node.
  28913. */
  28914. getPreviousTextureNode( name = 'output' ) {
  28915. let textureNode = this._previousTextureNodes[ name ];
  28916. if ( textureNode === undefined ) {
  28917. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  28918. textureNode = new PassMultipleTextureNode( this, name, true );
  28919. textureNode.updateTexture();
  28920. this._previousTextureNodes[ name ] = textureNode;
  28921. }
  28922. return textureNode;
  28923. }
  28924. /**
  28925. * Returns a viewZ node of this pass.
  28926. *
  28927. * @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.
  28928. * @return {Node} The viewZ node.
  28929. */
  28930. getViewZNode( name = 'depth' ) {
  28931. let viewZNode = this._viewZNodes[ name ];
  28932. if ( viewZNode === undefined ) {
  28933. const cameraNear = this._cameraNear;
  28934. const cameraFar = this._cameraFar;
  28935. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  28936. }
  28937. return viewZNode;
  28938. }
  28939. /**
  28940. * Returns a linear depth node of this pass.
  28941. *
  28942. * @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.
  28943. * @return {Node} The linear depth node.
  28944. */
  28945. getLinearDepthNode( name = 'depth' ) {
  28946. let linearDepthNode = this._linearDepthNodes[ name ];
  28947. if ( linearDepthNode === undefined ) {
  28948. const cameraNear = this._cameraNear;
  28949. const cameraFar = this._cameraFar;
  28950. const viewZNode = this.getViewZNode( name );
  28951. // TODO: just if ( builder.camera.isPerspectiveCamera )
  28952. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  28953. }
  28954. return linearDepthNode;
  28955. }
  28956. /**
  28957. * Precompiles the pass.
  28958. *
  28959. * Note that this method must be called after the pass configuration is complete.
  28960. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  28961. *
  28962. * @async
  28963. * @param {Renderer} renderer - The renderer.
  28964. * @return {Promise} A Promise that resolves when the compile has been finished.
  28965. * @see {@link Renderer#compileAsync}
  28966. */
  28967. async compileAsync( renderer ) {
  28968. const currentRenderTarget = renderer.getRenderTarget();
  28969. const currentMRT = renderer.getMRT();
  28970. renderer.setRenderTarget( this.renderTarget );
  28971. renderer.setMRT( this._mrt );
  28972. await renderer.compileAsync( this.scene, this.camera );
  28973. renderer.setRenderTarget( currentRenderTarget );
  28974. renderer.setMRT( currentMRT );
  28975. }
  28976. setup( { renderer } ) {
  28977. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  28978. this.renderTarget.texture.type = renderer.getOutputBufferType();
  28979. if ( renderer.reversedDepthBuffer === true && this.renderTarget.depthTexture !== null ) {
  28980. this.renderTarget.depthTexture.type = FloatType;
  28981. }
  28982. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  28983. }
  28984. updateBefore( frame ) {
  28985. const { renderer } = frame;
  28986. const { scene } = this;
  28987. let camera;
  28988. const outputRenderTarget = renderer.getOutputRenderTarget();
  28989. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  28990. camera = renderer.xr.getCamera();
  28991. renderer.xr.updateCamera( camera );
  28992. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  28993. } else {
  28994. camera = this.camera;
  28995. renderer.getDrawingBufferSize( _size );
  28996. }
  28997. this.setSize( _size.width, _size.height );
  28998. const currentRenderTarget = renderer.getRenderTarget();
  28999. const currentMRT = renderer.getMRT();
  29000. const currentAutoClear = renderer.autoClear;
  29001. const currentTransparent = renderer.transparent;
  29002. const currentOpaque = renderer.opaque;
  29003. const currentMask = camera.layers.mask;
  29004. const currentContextNode = renderer.contextNode;
  29005. const currentOverrideMaterial = scene.overrideMaterial;
  29006. this._cameraNear.value = camera.near;
  29007. this._cameraFar.value = camera.far;
  29008. if ( this._layers !== null ) {
  29009. camera.layers.mask = this._layers.mask;
  29010. }
  29011. for ( const name in this._previousTextures ) {
  29012. this.toggleTexture( name );
  29013. }
  29014. if ( this.overrideMaterial !== null ) {
  29015. scene.overrideMaterial = this.overrideMaterial;
  29016. }
  29017. renderer.setRenderTarget( this.renderTarget );
  29018. renderer.setMRT( this._mrt );
  29019. renderer.autoClear = true;
  29020. renderer.transparent = this.transparent;
  29021. renderer.opaque = this.opaque;
  29022. if ( this.contextNode !== null ) {
  29023. if ( this._contextNodeCache === null || this._contextNodeCache.version !== this.version ) {
  29024. this._contextNodeCache = {
  29025. version: this.version,
  29026. context: context( { ...renderer.contextNode.getFlowContextData(), ...this.contextNode.getFlowContextData() } )
  29027. };
  29028. }
  29029. renderer.contextNode = this._contextNodeCache.context;
  29030. }
  29031. const currentSceneName = scene.name;
  29032. scene.name = this.name ? this.name : scene.name;
  29033. renderer.render( scene, camera );
  29034. scene.name = currentSceneName;
  29035. scene.overrideMaterial = currentOverrideMaterial;
  29036. renderer.setRenderTarget( currentRenderTarget );
  29037. renderer.setMRT( currentMRT );
  29038. renderer.autoClear = currentAutoClear;
  29039. renderer.transparent = currentTransparent;
  29040. renderer.opaque = currentOpaque;
  29041. renderer.contextNode = currentContextNode;
  29042. camera.layers.mask = currentMask;
  29043. }
  29044. /**
  29045. * Sets the size of the pass's render target. Honors the pixel ratio.
  29046. *
  29047. * @param {number} width - The width to set.
  29048. * @param {number} height - The height to set.
  29049. */
  29050. setSize( width, height ) {
  29051. this._width = width;
  29052. this._height = height;
  29053. const effectiveWidth = Math.floor( this._width * this._resolutionScale );
  29054. const effectiveHeight = Math.floor( this._height * this._resolutionScale );
  29055. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  29056. // scissor
  29057. if ( this._scissor !== null ) {
  29058. this.renderTarget.scissor.copy( this._scissor ).multiplyScalar( this._resolutionScale ).floor();
  29059. this.renderTarget.scissorTest = true;
  29060. } else {
  29061. this.renderTarget.scissorTest = false;
  29062. }
  29063. // viewport
  29064. if ( this._viewport !== null ) {
  29065. this.renderTarget.viewport.copy( this._viewport ).multiplyScalar( this._resolutionScale ).floor();
  29066. }
  29067. }
  29068. /**
  29069. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  29070. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  29071. * with `null` as the single argument.
  29072. *
  29073. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  29074. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  29075. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  29076. * @param {number} width - The width of the scissor box in logical pixel unit.
  29077. * @param {number} height - The height of the scissor box in logical pixel unit.
  29078. */
  29079. setScissor( x, y, width, height ) {
  29080. if ( x === null ) {
  29081. this._scissor = null;
  29082. } else {
  29083. if ( this._scissor === null ) this._scissor = new Vector4();
  29084. if ( x.isVector4 ) {
  29085. this._scissor.copy( x );
  29086. } else {
  29087. this._scissor.set( x, y, width, height );
  29088. }
  29089. }
  29090. }
  29091. /**
  29092. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  29093. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  29094. * with `null` as the single argument.
  29095. *
  29096. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  29097. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  29098. * @param {number} width - The width of the viewport in logical pixel unit.
  29099. * @param {number} height - The height of the viewport in logical pixel unit.
  29100. */
  29101. setViewport( x, y, width, height ) {
  29102. if ( x === null ) {
  29103. this._viewport = null;
  29104. } else {
  29105. if ( this._viewport === null ) this._viewport = new Vector4();
  29106. if ( x.isVector4 ) {
  29107. this._viewport.copy( x );
  29108. } else {
  29109. this._viewport.set( x, y, width, height );
  29110. }
  29111. }
  29112. }
  29113. /**
  29114. * Frees internal resources. Should be called when the node is no longer in use.
  29115. */
  29116. dispose() {
  29117. this.renderTarget.dispose();
  29118. }
  29119. }
  29120. /**
  29121. * @static
  29122. * @type {'color'}
  29123. * @default 'color'
  29124. */
  29125. PassNode.COLOR = 'color';
  29126. /**
  29127. * @static
  29128. * @type {'depth'}
  29129. * @default 'depth'
  29130. */
  29131. PassNode.DEPTH = 'depth';
  29132. /**
  29133. * TSL function for creating a pass node.
  29134. *
  29135. * @tsl
  29136. * @function
  29137. * @param {Scene} scene - A reference to the scene.
  29138. * @param {Camera} camera - A reference to the camera.
  29139. * @param {Object} options - Options for the internal render target.
  29140. * @returns {PassNode}
  29141. */
  29142. const pass = ( scene, camera, options ) => new PassNode( PassNode.COLOR, scene, camera, options );
  29143. /**
  29144. * TSL function for creating a pass texture node.
  29145. *
  29146. * @tsl
  29147. * @function
  29148. * @param {PassNode} pass - The pass node.
  29149. * @param {Texture} texture - The output texture.
  29150. * @returns {PassTextureNode}
  29151. */
  29152. const passTexture = ( pass, texture ) => new PassTextureNode( pass, texture );
  29153. /**
  29154. * TSL function for creating a depth pass node.
  29155. *
  29156. * @tsl
  29157. * @function
  29158. * @param {Scene} scene - A reference to the scene.
  29159. * @param {Camera} camera - A reference to the camera.
  29160. * @param {Object} options - Options for the internal render target.
  29161. * @returns {PassNode}
  29162. */
  29163. const depthPass = ( scene, camera, options ) => new PassNode( PassNode.DEPTH, scene, camera, options );
  29164. /**
  29165. * Represents a render pass for producing a toon outline effect on compatible objects.
  29166. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  29167. * will receive the outline.
  29168. *
  29169. * ```js
  29170. * const postProcessing = new RenderPipeline( renderer );
  29171. *
  29172. * const scenePass = toonOutlinePass( scene, camera );
  29173. *
  29174. * postProcessing.outputNode = scenePass;
  29175. * ```
  29176. * @augments PassNode
  29177. */
  29178. class ToonOutlinePassNode extends PassNode {
  29179. static get type() {
  29180. return 'ToonOutlinePassNode';
  29181. }
  29182. /**
  29183. * Constructs a new outline pass node.
  29184. *
  29185. * @param {Scene} scene - A reference to the scene.
  29186. * @param {Camera} camera - A reference to the camera.
  29187. * @param {Node} colorNode - Defines the outline's color.
  29188. * @param {Node} thicknessNode - Defines the outline's thickness.
  29189. * @param {Node} alphaNode - Defines the outline's alpha.
  29190. */
  29191. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  29192. super( PassNode.COLOR, scene, camera );
  29193. /**
  29194. * Defines the outline's color.
  29195. *
  29196. * @type {Node}
  29197. */
  29198. this.colorNode = colorNode;
  29199. /**
  29200. * Defines the outline's thickness.
  29201. *
  29202. * @type {Node}
  29203. */
  29204. this.thicknessNode = thicknessNode;
  29205. /**
  29206. * Defines the outline's alpha.
  29207. *
  29208. * @type {Node}
  29209. */
  29210. this.alphaNode = alphaNode;
  29211. /**
  29212. * An internal material cache.
  29213. *
  29214. * @private
  29215. * @type {WeakMap<Material, NodeMaterial>}
  29216. */
  29217. this._materialCache = new WeakMap();
  29218. /**
  29219. * The name of this pass.
  29220. *
  29221. * @type {string}
  29222. * @default 'Outline Pass'
  29223. */
  29224. this.name = 'Outline Pass';
  29225. }
  29226. updateBefore( frame ) {
  29227. const { renderer } = frame;
  29228. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  29229. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  29230. // only render outline for supported materials
  29231. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  29232. if ( material.wireframe === false ) {
  29233. const outlineMaterial = this._getOutlineMaterial( material );
  29234. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  29235. }
  29236. }
  29237. // default
  29238. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  29239. } );
  29240. super.updateBefore( frame );
  29241. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  29242. }
  29243. /**
  29244. * Creates the material used for outline rendering.
  29245. *
  29246. * @private
  29247. * @return {NodeMaterial} The outline material.
  29248. */
  29249. _createMaterial() {
  29250. const material = new NodeMaterial();
  29251. material.isMeshToonOutlineMaterial = true;
  29252. material.name = 'Toon_Outline';
  29253. material.side = BackSide;
  29254. // vertex node
  29255. const outlineNormal = normalLocal.negate();
  29256. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  29257. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  29258. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  29259. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  29260. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  29261. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  29262. // color node
  29263. material.colorNode = vec4( this.colorNode, this.alphaNode );
  29264. return material;
  29265. }
  29266. /**
  29267. * For the given toon material, this method returns a corresponding
  29268. * outline material.
  29269. *
  29270. * @private
  29271. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  29272. * @return {NodeMaterial} The outline material.
  29273. */
  29274. _getOutlineMaterial( originalMaterial ) {
  29275. let outlineMaterial = this._materialCache.get( originalMaterial );
  29276. if ( outlineMaterial === undefined ) {
  29277. outlineMaterial = this._createMaterial();
  29278. this._materialCache.set( originalMaterial, outlineMaterial );
  29279. }
  29280. return outlineMaterial;
  29281. }
  29282. }
  29283. /**
  29284. * TSL function for creating a toon outline pass node.
  29285. *
  29286. * @tsl
  29287. * @function
  29288. * @param {Scene} scene - A reference to the scene.
  29289. * @param {Camera} camera - A reference to the camera.
  29290. * @param {Color} color - Defines the outline's color.
  29291. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  29292. * @param {number} [alpha=1] - Defines the outline's alpha.
  29293. * @returns {ToonOutlinePassNode}
  29294. */
  29295. 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 ) );
  29296. /**
  29297. * Linear tone mapping, exposure only.
  29298. *
  29299. * @tsl
  29300. * @function
  29301. * @param {Node<vec3>} color - The color that should be tone mapped.
  29302. * @param {Node<float>} exposure - The exposure.
  29303. * @return {Node<vec3>} The tone mapped color.
  29304. */
  29305. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  29306. return color.mul( exposure ).clamp();
  29307. } ).setLayout( {
  29308. name: 'linearToneMapping',
  29309. type: 'vec3',
  29310. inputs: [
  29311. { name: 'color', type: 'vec3' },
  29312. { name: 'exposure', type: 'float' }
  29313. ]
  29314. } );
  29315. /**
  29316. * Reinhard tone mapping.
  29317. *
  29318. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  29319. *
  29320. * @tsl
  29321. * @function
  29322. * @param {Node<vec3>} color - The color that should be tone mapped.
  29323. * @param {Node<float>} exposure - The exposure.
  29324. * @return {Node<vec3>} The tone mapped color.
  29325. */
  29326. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  29327. color = color.mul( exposure );
  29328. return color.div( color.add( 1.0 ) ).clamp();
  29329. } ).setLayout( {
  29330. name: 'reinhardToneMapping',
  29331. type: 'vec3',
  29332. inputs: [
  29333. { name: 'color', type: 'vec3' },
  29334. { name: 'exposure', type: 'float' }
  29335. ]
  29336. } );
  29337. /**
  29338. * Cineon tone mapping.
  29339. *
  29340. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  29341. *
  29342. * @tsl
  29343. * @function
  29344. * @param {Node<vec3>} color - The color that should be tone mapped.
  29345. * @param {Node<float>} exposure - The exposure.
  29346. * @return {Node<vec3>} The tone mapped color.
  29347. */
  29348. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  29349. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  29350. color = color.mul( exposure );
  29351. color = color.sub( 0.004 ).max( 0.0 );
  29352. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  29353. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  29354. return a.div( b ).pow( 2.2 );
  29355. } ).setLayout( {
  29356. name: 'cineonToneMapping',
  29357. type: 'vec3',
  29358. inputs: [
  29359. { name: 'color', type: 'vec3' },
  29360. { name: 'exposure', type: 'float' }
  29361. ]
  29362. } );
  29363. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  29364. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  29365. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  29366. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  29367. return a.div( b );
  29368. } );
  29369. /**
  29370. * ACESFilmic tone mapping.
  29371. *
  29372. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  29373. *
  29374. * @tsl
  29375. * @function
  29376. * @param {Node<vec3>} color - The color that should be tone mapped.
  29377. * @param {Node<float>} exposure - The exposure.
  29378. * @return {Node<vec3>} The tone mapped color.
  29379. */
  29380. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  29381. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  29382. const ACESInputMat = mat3(
  29383. 0.59719, 0.35458, 0.04823,
  29384. 0.07600, 0.90834, 0.01566,
  29385. 0.02840, 0.13383, 0.83777
  29386. );
  29387. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  29388. const ACESOutputMat = mat3(
  29389. 1.60475, -0.53108, -0.07367,
  29390. -0.10208, 1.10813, -605e-5,
  29391. -327e-5, -0.07276, 1.07602
  29392. );
  29393. color = color.mul( exposure ).div( 0.6 );
  29394. color = ACESInputMat.mul( color );
  29395. // Apply RRT and ODT
  29396. color = RRTAndODTFit( color );
  29397. color = ACESOutputMat.mul( color );
  29398. // Clamp to [0, 1]
  29399. return color.clamp();
  29400. } ).setLayout( {
  29401. name: 'acesFilmicToneMapping',
  29402. type: 'vec3',
  29403. inputs: [
  29404. { name: 'color', type: 'vec3' },
  29405. { name: 'exposure', type: 'float' }
  29406. ]
  29407. } );
  29408. 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 ) );
  29409. 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 ) );
  29410. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  29411. const x = vec3( x_immutable ).toVar();
  29412. const x2 = vec3( x.mul( x ) ).toVar();
  29413. const x4 = vec3( x2.mul( x2 ) ).toVar();
  29414. 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 ) ) ) );
  29415. } );
  29416. /**
  29417. * AgX tone mapping.
  29418. *
  29419. * @tsl
  29420. * @function
  29421. * @param {Node<vec3>} color - The color that should be tone mapped.
  29422. * @param {Node<float>} exposure - The exposure.
  29423. * @return {Node<vec3>} The tone mapped color.
  29424. */
  29425. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  29426. const colortone = vec3( color ).toVar();
  29427. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  29428. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  29429. const AgxMinEv = float( -12.47393 );
  29430. const AgxMaxEv = float( 4.026069 );
  29431. colortone.mulAssign( exposure );
  29432. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  29433. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  29434. colortone.assign( max$1( colortone, 1e-10 ) );
  29435. colortone.assign( log2( colortone ) );
  29436. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  29437. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  29438. colortone.assign( agxDefaultContrastApprox( colortone ) );
  29439. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  29440. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  29441. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  29442. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  29443. return colortone;
  29444. } ).setLayout( {
  29445. name: 'agxToneMapping',
  29446. type: 'vec3',
  29447. inputs: [
  29448. { name: 'color', type: 'vec3' },
  29449. { name: 'exposure', type: 'float' }
  29450. ]
  29451. } );
  29452. /**
  29453. * Neutral tone mapping.
  29454. *
  29455. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  29456. *
  29457. * @tsl
  29458. * @function
  29459. * @param {Node<vec3>} color - The color that should be tone mapped.
  29460. * @param {Node<float>} exposure - The exposure.
  29461. * @return {Node<vec3>} The tone mapped color.
  29462. */
  29463. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  29464. const StartCompression = float( 0.8 - 0.04 );
  29465. const Desaturation = float( 0.15 );
  29466. color = color.mul( exposure );
  29467. const x = min$1( color.r, min$1( color.g, color.b ) );
  29468. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  29469. color.subAssign( offset );
  29470. const peak = max$1( color.r, max$1( color.g, color.b ) );
  29471. If( peak.lessThan( StartCompression ), () => {
  29472. return color;
  29473. } );
  29474. const d = sub( 1, StartCompression );
  29475. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  29476. color.mulAssign( newPeak.div( peak ) );
  29477. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  29478. return mix( color, vec3( newPeak ), g );
  29479. } ).setLayout( {
  29480. name: 'neutralToneMapping',
  29481. type: 'vec3',
  29482. inputs: [
  29483. { name: 'color', type: 'vec3' },
  29484. { name: 'exposure', type: 'float' }
  29485. ]
  29486. } );
  29487. /**
  29488. * This class represents native code sections. It is the base
  29489. * class for modules like {@link FunctionNode} which allows to implement
  29490. * functions with native shader languages.
  29491. *
  29492. * @augments Node
  29493. */
  29494. class CodeNode extends Node {
  29495. static get type() {
  29496. return 'CodeNode';
  29497. }
  29498. /**
  29499. * Constructs a new code node.
  29500. *
  29501. * @param {string} [code=''] - The native code.
  29502. * @param {Array<Node>} [includes=[]] - An array of includes.
  29503. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  29504. */
  29505. constructor( code = '', includes = [], language = '' ) {
  29506. super( 'code' );
  29507. /**
  29508. * This flag can be used for type testing.
  29509. *
  29510. * @type {boolean}
  29511. * @readonly
  29512. * @default true
  29513. */
  29514. this.isCodeNode = true;
  29515. /**
  29516. * This flag is used for global cache.
  29517. *
  29518. * @type {boolean}
  29519. * @default true
  29520. */
  29521. this.global = true;
  29522. /**
  29523. * The native code.
  29524. *
  29525. * @type {string}
  29526. * @default ''
  29527. */
  29528. this.code = code;
  29529. /**
  29530. * An array of includes
  29531. *
  29532. * @type {Array<Node>}
  29533. * @default []
  29534. */
  29535. this.includes = includes;
  29536. /**
  29537. * The used language.
  29538. *
  29539. * @type {('js'|'wgsl'|'glsl')}
  29540. * @default ''
  29541. */
  29542. this.language = language;
  29543. }
  29544. /**
  29545. * Sets the includes of this code node.
  29546. *
  29547. * @param {Array<Node>} includes - The includes to set.
  29548. * @return {CodeNode} A reference to this node.
  29549. */
  29550. setIncludes( includes ) {
  29551. this.includes = includes;
  29552. return this;
  29553. }
  29554. /**
  29555. * Returns the includes of this code node.
  29556. *
  29557. * @param {NodeBuilder} builder - The current node builder.
  29558. * @return {Array<Node>} The includes.
  29559. */
  29560. getIncludes( /*builder*/ ) {
  29561. return this.includes;
  29562. }
  29563. generate( builder ) {
  29564. const includes = this.getIncludes( builder );
  29565. for ( const include of includes ) {
  29566. include.build( builder );
  29567. }
  29568. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  29569. nodeCode.code = this.code;
  29570. return nodeCode.code;
  29571. }
  29572. serialize( data ) {
  29573. super.serialize( data );
  29574. data.code = this.code;
  29575. data.language = this.language;
  29576. }
  29577. deserialize( data ) {
  29578. super.deserialize( data );
  29579. this.code = data.code;
  29580. this.language = data.language;
  29581. }
  29582. }
  29583. /**
  29584. * TSL function for creating a code node.
  29585. *
  29586. * @tsl
  29587. * @function
  29588. * @param {string} [code] - The native code.
  29589. * @param {?Array<Node>} [includes=[]] - An array of includes.
  29590. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  29591. * @returns {CodeNode}
  29592. */
  29593. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  29594. /**
  29595. * TSL function for creating a JS code node.
  29596. *
  29597. * @tsl
  29598. * @function
  29599. * @param {string} src - The native code.
  29600. * @param {Array<Node>} includes - An array of includes.
  29601. * @returns {CodeNode}
  29602. */
  29603. const js = ( src, includes ) => code( src, includes, 'js' );
  29604. /**
  29605. * TSL function for creating a WGSL code node.
  29606. *
  29607. * @tsl
  29608. * @function
  29609. * @param {string} src - The native code.
  29610. * @param {Array<Node>} includes - An array of includes.
  29611. * @returns {CodeNode}
  29612. */
  29613. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  29614. /**
  29615. * TSL function for creating a GLSL code node.
  29616. *
  29617. * @tsl
  29618. * @function
  29619. * @param {string} src - The native code.
  29620. * @param {Array<Node>} includes - An array of includes.
  29621. * @returns {CodeNode}
  29622. */
  29623. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  29624. /**
  29625. * This class represents a native shader function. It can be used to implement
  29626. * certain aspects of a node material with native shader code. There are two predefined
  29627. * TSL functions for easier usage.
  29628. *
  29629. * - `wgslFn`: Creates a WGSL function node.
  29630. * - `glslFn`: Creates a GLSL function node.
  29631. *
  29632. * A basic example with one include looks like so:
  29633. *
  29634. * ```js
  29635. * const desaturateWGSLFn = wgslFn( `
  29636. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  29637. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  29638. * return vec3<f32>( dot( lum, color ) );
  29639. * }`
  29640. *);
  29641. * const someWGSLFn = wgslFn( `
  29642. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  29643. * return desaturate( color );
  29644. * }
  29645. * `, [ desaturateWGSLFn ] );
  29646. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  29647. *```
  29648. * @augments CodeNode
  29649. */
  29650. class FunctionNode extends CodeNode {
  29651. static get type() {
  29652. return 'FunctionNode';
  29653. }
  29654. /**
  29655. * Constructs a new function node.
  29656. *
  29657. * @param {string} [code=''] - The native code.
  29658. * @param {Array<Node>} [includes=[]] - An array of includes.
  29659. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  29660. */
  29661. constructor( code = '', includes = [], language = '' ) {
  29662. super( code, includes, language );
  29663. }
  29664. /**
  29665. * Returns the type of this function node.
  29666. *
  29667. * @param {NodeBuilder} builder - The current node builder.
  29668. * @return {string} The type.
  29669. */
  29670. generateNodeType( builder ) {
  29671. return this.getNodeFunction( builder ).type;
  29672. }
  29673. /**
  29674. * Returns the type of a member of this function node.
  29675. *
  29676. * @param {NodeBuilder} builder - The current node builder.
  29677. * @param {string} name - The name of the member.
  29678. * @return {string} The type of the member.
  29679. */
  29680. getMemberType( builder, name ) {
  29681. const type = this.getNodeType( builder );
  29682. const structType = builder.getStructTypeNode( type );
  29683. return structType.getMemberType( builder, name );
  29684. }
  29685. /**
  29686. * Returns the inputs of this function node.
  29687. *
  29688. * @param {NodeBuilder} builder - The current node builder.
  29689. * @return {Array<NodeFunctionInput>} The inputs.
  29690. */
  29691. getInputs( builder ) {
  29692. return this.getNodeFunction( builder ).inputs;
  29693. }
  29694. /**
  29695. * Returns the node function for this function node.
  29696. *
  29697. * @param {NodeBuilder} builder - The current node builder.
  29698. * @return {NodeFunction} The node function.
  29699. */
  29700. getNodeFunction( builder ) {
  29701. const nodeData = builder.getDataFromNode( this );
  29702. let nodeFunction = nodeData.nodeFunction;
  29703. if ( nodeFunction === undefined ) {
  29704. nodeFunction = builder.parser.parseFunction( this.code );
  29705. nodeData.nodeFunction = nodeFunction;
  29706. }
  29707. return nodeFunction;
  29708. }
  29709. generate( builder, output ) {
  29710. super.generate( builder );
  29711. const nodeFunction = this.getNodeFunction( builder );
  29712. const name = nodeFunction.name;
  29713. const type = nodeFunction.type;
  29714. const nodeCode = builder.getCodeFromNode( this, type );
  29715. if ( name !== '' ) {
  29716. // use a custom property name
  29717. nodeCode.name = name;
  29718. }
  29719. const propertyName = builder.getPropertyName( nodeCode );
  29720. const code = this.getNodeFunction( builder ).getCode( propertyName );
  29721. nodeCode.code = code + '\n';
  29722. if ( output === 'property' ) {
  29723. return propertyName;
  29724. } else {
  29725. return builder.format( `${ propertyName }()`, type, output );
  29726. }
  29727. }
  29728. }
  29729. const nativeFn = ( code, includes = [], language = '' ) => {
  29730. const functionNode = new FunctionNode( code, includes, language );
  29731. const fn = ( ...params ) => functionNode.call( ...params );
  29732. return nodeProxyConstructor( fn, functionNode );
  29733. };
  29734. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  29735. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  29736. /**
  29737. * Returns a node that represents the `z` coordinate in view space
  29738. * for the current fragment. It's a different representation of the
  29739. * default depth value.
  29740. *
  29741. * This value can be part of a computation that defines how the fog
  29742. * density increases when moving away from the camera.
  29743. *
  29744. * @param {NodeBuilder} builder - The current node builder.
  29745. * @return {Node} The viewZ node.
  29746. */
  29747. function getViewZNode( builder ) {
  29748. let viewZ;
  29749. const getViewZ = builder.context.getViewZ;
  29750. if ( getViewZ !== undefined ) {
  29751. viewZ = getViewZ( this );
  29752. }
  29753. return ( viewZ || positionView.z ).negate();
  29754. }
  29755. /**
  29756. * Constructs a new range factor node.
  29757. *
  29758. * @tsl
  29759. * @function
  29760. * @param {Node} near - Defines the near value.
  29761. * @param {Node} far - Defines the far value.
  29762. */
  29763. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  29764. const viewZ = getViewZNode( builder );
  29765. return smoothstep( near, far, viewZ );
  29766. } );
  29767. /**
  29768. * Represents an exponential squared fog. This type of fog gives
  29769. * a clear view near the camera and a faster than exponentially
  29770. * densening fog farther from the camera.
  29771. *
  29772. * @tsl
  29773. * @function
  29774. * @param {Node} density - Defines the fog density.
  29775. */
  29776. const densityFogFactor = Fn( ( [ density ], builder ) => {
  29777. const viewZ = getViewZNode( builder );
  29778. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  29779. } );
  29780. /**
  29781. * Constructs a new height fog factor node. This fog factor requires a Y-up coordinate system.
  29782. *
  29783. * @tsl
  29784. * @function
  29785. * @param {Node} density - Defines the fog density.
  29786. * @param {Node} height - The height threshold in world space. Everything below this y-coordinate is affected by fog.
  29787. */
  29788. const exponentialHeightFogFactor = Fn( ( [ density, height ], builder ) => {
  29789. const viewZ = getViewZNode( builder );
  29790. const distance = height.sub( positionWorld.y ).max( 0 ).toConst();
  29791. const m = distance.mul( viewZ ).toConst();
  29792. return density.mul( density, m, m ).negate().exp().oneMinus();
  29793. } );
  29794. /**
  29795. * This class can be used to configure a fog for the scene.
  29796. * Nodes of this type are assigned to `Scene.fogNode`.
  29797. *
  29798. * @tsl
  29799. * @function
  29800. * @param {Node} color - Defines the color of the fog.
  29801. * @param {Node} factor - Defines how the fog is factored in the scene.
  29802. */
  29803. const fog = Fn( ( [ color, factor ] ) => {
  29804. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  29805. } );
  29806. let min = null;
  29807. let max = null;
  29808. /**
  29809. * `RangeNode` generates random instanced attribute data in a defined range.
  29810. * An exemplary use case for this utility node is to generate random per-instance
  29811. * colors:
  29812. * ```js
  29813. * const material = new MeshBasicNodeMaterial();
  29814. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  29815. * const mesh = new InstancedMesh( geometry, material, count );
  29816. * ```
  29817. * @augments Node
  29818. */
  29819. class RangeNode extends Node {
  29820. static get type() {
  29821. return 'RangeNode';
  29822. }
  29823. /**
  29824. * Constructs a new range node.
  29825. *
  29826. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  29827. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  29828. */
  29829. constructor( minNode = float(), maxNode = float() ) {
  29830. super();
  29831. /**
  29832. * A node defining the lower bound of the range.
  29833. *
  29834. * @type {Node<any>}
  29835. * @default float()
  29836. */
  29837. this.minNode = minNode;
  29838. /**
  29839. * A node defining the upper bound of the range.
  29840. *
  29841. * @type {Node<any>}
  29842. * @default float()
  29843. */
  29844. this.maxNode = maxNode;
  29845. }
  29846. /**
  29847. * Returns the vector length which is computed based on the range definition.
  29848. *
  29849. * @param {NodeBuilder} builder - The current node builder.
  29850. * @return {number} The vector length.
  29851. */
  29852. getVectorLength( builder ) {
  29853. const minNode = this.getConstNode( this.minNode );
  29854. const maxNode = this.getConstNode( this.maxNode );
  29855. const minLength = builder.getTypeLength( getValueType( minNode.value ) );
  29856. const maxLength = builder.getTypeLength( getValueType( maxNode.value ) );
  29857. return minLength > maxLength ? minLength : maxLength;
  29858. }
  29859. /**
  29860. * This method is overwritten since the node type is inferred from range definition.
  29861. *
  29862. * @param {NodeBuilder} builder - The current node builder.
  29863. * @return {string} The node type.
  29864. */
  29865. generateNodeType( builder ) {
  29866. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  29867. }
  29868. /**
  29869. * Returns a constant node from the given node by traversing it.
  29870. *
  29871. * @param {Node} node - The node to traverse.
  29872. * @returns {Node} The constant node, if found.
  29873. */
  29874. getConstNode( node ) {
  29875. let output = null;
  29876. node.traverse( n => {
  29877. if ( n.isConstNode === true ) {
  29878. output = n;
  29879. }
  29880. } );
  29881. if ( output === null ) {
  29882. throw new NodeError( 'THREE.TSL: No "ConstNode" found in node graph.', this.stackTrace );
  29883. }
  29884. return output;
  29885. }
  29886. setup( builder ) {
  29887. const object = builder.object;
  29888. let output = null;
  29889. if ( object.count > 1 ) {
  29890. const minNode = this.getConstNode( this.minNode );
  29891. const maxNode = this.getConstNode( this.maxNode );
  29892. const minValue = minNode.value;
  29893. const maxValue = maxNode.value;
  29894. const minLength = builder.getTypeLength( getValueType( minValue ) );
  29895. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  29896. min = min || new Vector4();
  29897. max = max || new Vector4();
  29898. min.setScalar( 0 );
  29899. max.setScalar( 0 );
  29900. if ( minLength === 1 ) min.setScalar( minValue );
  29901. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  29902. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  29903. if ( maxLength === 1 ) max.setScalar( maxValue );
  29904. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  29905. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  29906. const stride = 4;
  29907. const length = stride * object.count;
  29908. const array = new Float32Array( length );
  29909. for ( let i = 0; i < length; i ++ ) {
  29910. const index = i % stride;
  29911. const minElementValue = min.getComponent( index );
  29912. const maxElementValue = max.getComponent( index );
  29913. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  29914. }
  29915. const nodeType = this.getNodeType( builder );
  29916. const uniformBufferSize = object.count * 4 * 4; // count * 4 components * 4 bytes (float)
  29917. if ( uniformBufferSize <= builder.getUniformBufferLimit() ) {
  29918. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  29919. } else {
  29920. // TODO: Improve anonymous buffer attribute creation removing this part
  29921. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  29922. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  29923. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  29924. }
  29925. } else {
  29926. output = float( 0 );
  29927. }
  29928. return output;
  29929. }
  29930. }
  29931. /**
  29932. * TSL function for creating a range node.
  29933. *
  29934. * @tsl
  29935. * @function
  29936. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  29937. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  29938. * @returns {RangeNode}
  29939. */
  29940. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  29941. /**
  29942. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  29943. * about the currently running dispatch and/or the device it is running on.
  29944. *
  29945. * This node can only be used with a WebGPU backend.
  29946. *
  29947. * @augments Node
  29948. */
  29949. class ComputeBuiltinNode extends Node {
  29950. static get type() {
  29951. return 'ComputeBuiltinNode';
  29952. }
  29953. /**
  29954. * Constructs a new compute builtin node.
  29955. *
  29956. * @param {string} builtinName - The built-in name.
  29957. * @param {string} nodeType - The node type.
  29958. */
  29959. constructor( builtinName, nodeType ) {
  29960. super( nodeType );
  29961. /**
  29962. * The built-in name.
  29963. *
  29964. * @private
  29965. * @type {string}
  29966. */
  29967. this._builtinName = builtinName;
  29968. }
  29969. /**
  29970. * This method is overwritten since hash is derived from the built-in name.
  29971. *
  29972. * @param {NodeBuilder} builder - The current node builder.
  29973. * @return {string} The hash.
  29974. */
  29975. getHash( builder ) {
  29976. return this.getBuiltinName( builder );
  29977. }
  29978. /**
  29979. * This method is overwritten since the node type is simply derived from `nodeType`..
  29980. *
  29981. * @param {NodeBuilder} builder - The current node builder.
  29982. * @return {string} The node type.
  29983. */
  29984. generateNodeType( /*builder*/ ) {
  29985. return this.nodeType;
  29986. }
  29987. /**
  29988. * Sets the builtin name.
  29989. *
  29990. * @param {string} builtinName - The built-in name.
  29991. * @return {ComputeBuiltinNode} A reference to this node.
  29992. */
  29993. setBuiltinName( builtinName ) {
  29994. this._builtinName = builtinName;
  29995. return this;
  29996. }
  29997. /**
  29998. * Returns the builtin name.
  29999. *
  30000. * @param {NodeBuilder} builder - The current node builder.
  30001. * @return {string} The builtin name.
  30002. */
  30003. getBuiltinName( /*builder*/ ) {
  30004. return this._builtinName;
  30005. }
  30006. /**
  30007. * Whether the current node builder has the builtin or not.
  30008. *
  30009. * @param {NodeBuilder} builder - The current node builder.
  30010. * @return {boolean} Whether the builder has the builtin or not.
  30011. */
  30012. hasBuiltin( builder ) {
  30013. return builder.hasBuiltin( this._builtinName );
  30014. }
  30015. generate( builder, output ) {
  30016. const builtinName = this.getBuiltinName( builder );
  30017. const nodeType = this.getNodeType( builder );
  30018. if ( builder.shaderStage === 'compute' ) {
  30019. return builder.format( builtinName, nodeType, output );
  30020. } else {
  30021. warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  30022. return builder.generateConst( nodeType );
  30023. }
  30024. }
  30025. serialize( data ) {
  30026. super.serialize( data );
  30027. data.global = this.global;
  30028. data._builtinName = this._builtinName;
  30029. }
  30030. deserialize( data ) {
  30031. super.deserialize( data );
  30032. this.global = data.global;
  30033. this._builtinName = data._builtinName;
  30034. }
  30035. }
  30036. /**
  30037. * TSL function for creating a compute builtin node.
  30038. *
  30039. * @tsl
  30040. * @function
  30041. * @param {string} name - The built-in name.
  30042. * @param {string} nodeType - The node type.
  30043. * @returns {ComputeBuiltinNode}
  30044. */
  30045. const computeBuiltin = ( name, nodeType ) => new ComputeBuiltinNode( name, nodeType );
  30046. /**
  30047. * Represents the number of workgroups dispatched by the compute shader.
  30048. * ```js
  30049. * // Run 512 invocations/threads with a workgroup size of 128.
  30050. * const computeFn = Fn(() => {
  30051. *
  30052. * // numWorkgroups.x = 4
  30053. * storageBuffer.element(0).assign(numWorkgroups.x)
  30054. *
  30055. * })().compute(512, [128]);
  30056. *
  30057. * // Run 512 invocations/threads with the default workgroup size of 64.
  30058. * const computeFn = Fn(() => {
  30059. *
  30060. * // numWorkgroups.x = 8
  30061. * storageBuffer.element(0).assign(numWorkgroups.x)
  30062. *
  30063. * })().compute(512);
  30064. * ```
  30065. *
  30066. * @tsl
  30067. * @type {ComputeBuiltinNode<uvec3>}
  30068. */
  30069. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  30070. /**
  30071. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  30072. * ```js
  30073. * // Execute 12 compute threads with a workgroup size of 3.
  30074. * const computeFn = Fn( () => {
  30075. *
  30076. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  30077. *
  30078. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  30079. *
  30080. * } ).Else( () => {
  30081. *
  30082. * storageBuffer.element( instanceIndex ).assign( 0 );
  30083. *
  30084. * } );
  30085. *
  30086. * } )().compute( 12, [ 3 ] );
  30087. *
  30088. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  30089. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  30090. * ```
  30091. *
  30092. * @tsl
  30093. * @type {ComputeBuiltinNode<uvec3>}
  30094. */
  30095. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  30096. /**
  30097. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  30098. *
  30099. * @tsl
  30100. * @type {ComputeBuiltinNode<uvec3>}
  30101. */
  30102. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  30103. /**
  30104. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  30105. *
  30106. * @tsl
  30107. * @type {ComputeBuiltinNode<uvec3>}
  30108. */
  30109. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  30110. /**
  30111. * A device dependent variable that exposes the size of the current invocation's subgroup.
  30112. *
  30113. * @tsl
  30114. * @type {ComputeBuiltinNode<uint>}
  30115. */
  30116. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  30117. /**
  30118. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  30119. *
  30120. * This node can only be used with a WebGPU backend.
  30121. *
  30122. * @augments Node
  30123. */
  30124. class BarrierNode extends Node {
  30125. /**
  30126. * Constructs a new barrier node.
  30127. *
  30128. * @param {string} scope - The scope defines the behavior of the node.
  30129. */
  30130. constructor( scope ) {
  30131. super();
  30132. this.scope = scope;
  30133. this.isBarrierNode = true;
  30134. }
  30135. setup( builder ) {
  30136. builder.allowEarlyReturns = false;
  30137. builder.allowGlobalVariables = false;
  30138. }
  30139. generate( builder ) {
  30140. const { scope } = this;
  30141. const { renderer } = builder;
  30142. if ( renderer.backend.isWebGLBackend === true ) {
  30143. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  30144. } else {
  30145. builder.addLineFlowCode( `${scope}Barrier()`, this );
  30146. }
  30147. }
  30148. }
  30149. /**
  30150. * TSL function for creating a barrier node.
  30151. *
  30152. * @tsl
  30153. * @function
  30154. * @param {string} scope - The scope defines the behavior of the node..
  30155. * @returns {BarrierNode}
  30156. */
  30157. const barrier = nodeProxy( BarrierNode );
  30158. /**
  30159. * TSL function for creating a workgroup barrier. All compute shader
  30160. * invocations must wait for each invocation within a workgroup to
  30161. * complete before the barrier can be surpassed.
  30162. *
  30163. * @tsl
  30164. * @function
  30165. * @returns {BarrierNode}
  30166. */
  30167. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  30168. /**
  30169. * TSL function for creating a storage barrier. All invocations must
  30170. * wait for each access to variables within the 'storage' address space
  30171. * to complete before the barrier can be passed.
  30172. *
  30173. * @tsl
  30174. * @function
  30175. * @returns {BarrierNode}
  30176. */
  30177. const storageBarrier = () => barrier( 'storage' ).toStack();
  30178. /**
  30179. * TSL function for creating a texture barrier. All invocations must
  30180. * wait for each access to variables within the 'texture' address space
  30181. * to complete before the barrier can be passed.
  30182. *
  30183. * @tsl
  30184. * @function
  30185. * @returns {BarrierNode}
  30186. */
  30187. const textureBarrier = () => barrier( 'texture' ).toStack();
  30188. /**
  30189. * Represents an element of a 'workgroup' scoped buffer.
  30190. *
  30191. * @augments ArrayElementNode
  30192. */
  30193. class WorkgroupInfoElementNode extends ArrayElementNode {
  30194. /**
  30195. * Constructs a new workgroup info element node.
  30196. *
  30197. * @param {Node} workgroupInfoNode - The workgroup info node.
  30198. * @param {Node} indexNode - The index node that defines the element access.
  30199. */
  30200. constructor( workgroupInfoNode, indexNode ) {
  30201. super( workgroupInfoNode, indexNode );
  30202. /**
  30203. * This flag can be used for type testing.
  30204. *
  30205. * @type {boolean}
  30206. * @readonly
  30207. * @default true
  30208. */
  30209. this.isWorkgroupInfoElementNode = true;
  30210. }
  30211. generate( builder, output ) {
  30212. let snippet;
  30213. const isAssignContext = builder.isContextAssign();
  30214. snippet = super.generate( builder );
  30215. if ( isAssignContext !== true ) {
  30216. const type = this.getNodeType( builder );
  30217. snippet = builder.format( snippet, type, output );
  30218. }
  30219. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  30220. return snippet;
  30221. }
  30222. }
  30223. /**
  30224. * A node allowing the user to create a 'workgroup' scoped buffer within the
  30225. * context of a compute shader. Typically, workgroup scoped buffers are
  30226. * created to hold data that is transferred from a global storage scope into
  30227. * a local workgroup scope. For invocations within a workgroup, data
  30228. * access speeds on 'workgroup' scoped buffers can be significantly faster
  30229. * than similar access operations on globally accessible storage buffers.
  30230. *
  30231. * This node can only be used with a WebGPU backend.
  30232. *
  30233. * @augments Node
  30234. */
  30235. class WorkgroupInfoNode extends Node {
  30236. /**
  30237. * Constructs a new buffer scoped to type scope.
  30238. *
  30239. * @param {string} scope - TODO.
  30240. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  30241. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  30242. */
  30243. constructor( scope, bufferType, bufferCount = 0 ) {
  30244. super( bufferType );
  30245. /**
  30246. * The buffer type.
  30247. *
  30248. * @type {string}
  30249. */
  30250. this.bufferType = bufferType;
  30251. /**
  30252. * The buffer count.
  30253. *
  30254. * @type {number}
  30255. * @default 0
  30256. */
  30257. this.bufferCount = bufferCount;
  30258. /**
  30259. * This flag can be used for type testing.
  30260. *
  30261. * @type {boolean}
  30262. * @readonly
  30263. * @default true
  30264. */
  30265. this.isWorkgroupInfoNode = true;
  30266. /**
  30267. * The data type of the array buffer.
  30268. *
  30269. * @type {string}
  30270. */
  30271. this.elementType = bufferType;
  30272. /**
  30273. * TODO.
  30274. *
  30275. * @type {string}
  30276. */
  30277. this.scope = scope;
  30278. /**
  30279. * The name of the workgroup scoped buffer.
  30280. *
  30281. * @type {string}
  30282. * @default ''
  30283. */
  30284. this.name = '';
  30285. }
  30286. /**
  30287. * Sets the name of this node.
  30288. *
  30289. * @param {string} name - The name to set.
  30290. * @return {WorkgroupInfoNode} A reference to this node.
  30291. */
  30292. setName( name ) {
  30293. this.name = name;
  30294. return this;
  30295. }
  30296. /**
  30297. * Sets the name/label of this node.
  30298. *
  30299. * @deprecated
  30300. * @param {string} name - The name to set.
  30301. * @return {WorkgroupInfoNode} A reference to this node.
  30302. */
  30303. label( name ) {
  30304. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.', new StackTrace() ); // @deprecated r179
  30305. return this.setName( name );
  30306. }
  30307. /**
  30308. * Sets the scope of this node.
  30309. *
  30310. * @param {string} scope - The scope to set.
  30311. * @return {WorkgroupInfoNode} A reference to this node.
  30312. */
  30313. setScope( scope ) {
  30314. this.scope = scope;
  30315. return this;
  30316. }
  30317. /**
  30318. * The data type of the array buffer.
  30319. *
  30320. * @return {string} The element type.
  30321. */
  30322. getElementType() {
  30323. return this.elementType;
  30324. }
  30325. /**
  30326. * Overwrites the default implementation since the input type
  30327. * is inferred from the scope.
  30328. *
  30329. * @param {NodeBuilder} builder - The current node builder.
  30330. * @return {string} The input type.
  30331. */
  30332. getInputType( /*builder*/ ) {
  30333. return `${this.scope}Array`;
  30334. }
  30335. /**
  30336. * This method can be used to access elements via an index node.
  30337. *
  30338. * @param {IndexNode} indexNode - indexNode.
  30339. * @return {WorkgroupInfoElementNode} A reference to an element.
  30340. */
  30341. element( indexNode ) {
  30342. return new WorkgroupInfoElementNode( this, indexNode );
  30343. }
  30344. generate( builder ) {
  30345. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  30346. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  30347. }
  30348. }
  30349. /**
  30350. * TSL function for creating a workgroup info node.
  30351. * Creates a new 'workgroup' scoped array buffer.
  30352. *
  30353. * @tsl
  30354. * @function
  30355. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  30356. * @param {number} [count=0] - The number of elements in the buffer.
  30357. * @returns {WorkgroupInfoNode}
  30358. */
  30359. const workgroupArray = ( type, count ) => new WorkgroupInfoNode( 'Workgroup', type, count );
  30360. /**
  30361. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  30362. * within a shader. In an atomic function, any modification to an atomic variable will
  30363. * occur as an indivisible step with a defined order relative to other modifications.
  30364. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  30365. * atomic operations will not interfere with each other.
  30366. *
  30367. * This node can only be used with a WebGPU backend.
  30368. *
  30369. * @augments Node
  30370. */
  30371. class AtomicFunctionNode extends Node {
  30372. static get type() {
  30373. return 'AtomicFunctionNode';
  30374. }
  30375. /**
  30376. * Constructs a new atomic function node.
  30377. *
  30378. * @param {string} method - The signature of the atomic function to construct.
  30379. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30380. * @param {Node} valueNode - The value that mutates the atomic variable.
  30381. */
  30382. constructor( method, pointerNode, valueNode ) {
  30383. super( 'uint' );
  30384. /**
  30385. * The signature of the atomic function to construct.
  30386. *
  30387. * @type {string}
  30388. */
  30389. this.method = method;
  30390. /**
  30391. * An atomic variable or element of an atomic buffer.
  30392. *
  30393. * @type {Node}
  30394. */
  30395. this.pointerNode = pointerNode;
  30396. /**
  30397. * A value that modifies the atomic variable.
  30398. *
  30399. * @type {Node}
  30400. */
  30401. this.valueNode = valueNode;
  30402. /**
  30403. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  30404. *
  30405. * @type {boolean}
  30406. * @default true
  30407. */
  30408. this.parents = true;
  30409. }
  30410. /**
  30411. * Overwrites the default implementation to return the type of
  30412. * the pointer node.
  30413. *
  30414. * @param {NodeBuilder} builder - The current node builder.
  30415. * @return {string} The input type.
  30416. */
  30417. getInputType( builder ) {
  30418. return this.pointerNode.getNodeType( builder );
  30419. }
  30420. /**
  30421. * Overwritten since the node type is inferred from the input type.
  30422. *
  30423. * @param {NodeBuilder} builder - The current node builder.
  30424. * @return {string} The node type.
  30425. */
  30426. generateNodeType( builder ) {
  30427. return this.getInputType( builder );
  30428. }
  30429. generate( builder ) {
  30430. const properties = builder.getNodeProperties( this );
  30431. const parents = properties.parents;
  30432. const method = this.method;
  30433. const type = this.getNodeType( builder );
  30434. const inputType = this.getInputType( builder );
  30435. const a = this.pointerNode;
  30436. const b = this.valueNode;
  30437. const params = [];
  30438. params.push( `&${ a.build( builder, inputType ) }` );
  30439. if ( b !== null ) {
  30440. params.push( b.build( builder, inputType ) );
  30441. }
  30442. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  30443. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  30444. if ( isVoid ) {
  30445. builder.addLineFlowCode( methodSnippet, this );
  30446. } else {
  30447. if ( properties.constNode === undefined ) {
  30448. properties.constNode = expression( methodSnippet, type ).toConst();
  30449. }
  30450. return properties.constNode.build( builder );
  30451. }
  30452. }
  30453. }
  30454. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  30455. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  30456. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  30457. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  30458. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  30459. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  30460. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  30461. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  30462. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  30463. /**
  30464. * TSL function for creating an atomic function node.
  30465. *
  30466. * @tsl
  30467. * @function
  30468. * @param {string} method - The signature of the atomic function to construct.
  30469. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30470. * @param {Node} valueNode - The value that mutates the atomic variable.
  30471. * @returns {AtomicFunctionNode}
  30472. */
  30473. const atomicNode = nodeProxy( AtomicFunctionNode );
  30474. /**
  30475. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  30476. *
  30477. * @tsl
  30478. * @function
  30479. * @param {string} method - The signature of the atomic function to construct.
  30480. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30481. * @param {Node} valueNode - The value that mutates the atomic variable.
  30482. * @returns {AtomicFunctionNode}
  30483. */
  30484. const atomicFunc = ( method, pointerNode, valueNode ) => {
  30485. return atomicNode( method, pointerNode, valueNode ).toStack();
  30486. };
  30487. /**
  30488. * Loads the value stored in the atomic variable.
  30489. *
  30490. * @tsl
  30491. * @function
  30492. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30493. * @returns {AtomicFunctionNode}
  30494. */
  30495. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  30496. /**
  30497. * Stores a value in the atomic variable.
  30498. *
  30499. * @tsl
  30500. * @function
  30501. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30502. * @param {Node} valueNode - The value that mutates the atomic variable.
  30503. * @returns {AtomicFunctionNode}
  30504. */
  30505. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  30506. /**
  30507. * Increments the value stored in the atomic variable.
  30508. *
  30509. * @tsl
  30510. * @function
  30511. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30512. * @param {Node} valueNode - The value that mutates the atomic variable.
  30513. * @returns {AtomicFunctionNode}
  30514. */
  30515. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  30516. /**
  30517. * Decrements the value stored in the atomic variable.
  30518. *
  30519. * @tsl
  30520. * @function
  30521. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30522. * @param {Node} valueNode - The value that mutates the atomic variable.
  30523. * @returns {AtomicFunctionNode}
  30524. */
  30525. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  30526. /**
  30527. * Stores in an atomic variable the maximum between its current value and a parameter.
  30528. *
  30529. * @tsl
  30530. * @function
  30531. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30532. * @param {Node} valueNode - The value that mutates the atomic variable.
  30533. * @returns {AtomicFunctionNode}
  30534. */
  30535. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  30536. /**
  30537. * Stores in an atomic variable the minimum between its current value and a parameter.
  30538. *
  30539. * @tsl
  30540. * @function
  30541. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30542. * @param {Node} valueNode - The value that mutates the atomic variable.
  30543. * @returns {AtomicFunctionNode}
  30544. */
  30545. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  30546. /**
  30547. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  30548. *
  30549. * @tsl
  30550. * @function
  30551. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30552. * @param {Node} valueNode - The value that mutates the atomic variable.
  30553. * @returns {AtomicFunctionNode}
  30554. */
  30555. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  30556. /**
  30557. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  30558. *
  30559. * @tsl
  30560. * @function
  30561. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30562. * @param {Node} valueNode - The value that mutates the atomic variable.
  30563. * @returns {AtomicFunctionNode}
  30564. */
  30565. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  30566. /**
  30567. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  30568. *
  30569. * @tsl
  30570. * @function
  30571. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30572. * @param {Node} valueNode - The value that mutates the atomic variable.
  30573. * @returns {AtomicFunctionNode}
  30574. */
  30575. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  30576. /**
  30577. * This class represents a set of built in WGSL shader functions that sync
  30578. * synchronously execute an operation across a subgroup, or 'warp', of compute
  30579. * or fragment shader invocations within a workgroup. Typically, these functions
  30580. * will synchronously execute an operation using data from all active invocations
  30581. * within the subgroup, then broadcast that result to all active invocations. In
  30582. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  30583. * (DirectX/HLSL) or warp intrinsics (CUDA).
  30584. *
  30585. * @augments TempNode
  30586. */
  30587. class SubgroupFunctionNode extends TempNode {
  30588. static get type() {
  30589. return 'SubgroupFunctionNode';
  30590. }
  30591. /**
  30592. * Constructs a new function node.
  30593. *
  30594. * @param {string} method - The subgroup/wave intrinsic method to construct.
  30595. * @param {Node} [aNode=null] - The method's first argument.
  30596. * @param {Node} [bNode=null] - The method's second argument.
  30597. */
  30598. constructor( method, aNode = null, bNode = null ) {
  30599. super();
  30600. /**
  30601. * The subgroup/wave intrinsic method to construct.
  30602. *
  30603. * @type {string}
  30604. */
  30605. this.method = method;
  30606. /**
  30607. * The method's first argument.
  30608. *
  30609. * @type {Node}
  30610. */
  30611. this.aNode = aNode;
  30612. /**
  30613. * The method's second argument.
  30614. *
  30615. * @type {Node}
  30616. */
  30617. this.bNode = bNode;
  30618. }
  30619. getInputType( builder ) {
  30620. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  30621. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  30622. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  30623. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  30624. if ( aLen > bLen ) {
  30625. return aType;
  30626. } else {
  30627. return bType;
  30628. }
  30629. }
  30630. generateNodeType( builder ) {
  30631. const method = this.method;
  30632. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  30633. return 'bool';
  30634. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  30635. return 'uvec4';
  30636. } else {
  30637. return this.getInputType( builder );
  30638. }
  30639. }
  30640. generate( builder, output ) {
  30641. const method = this.method;
  30642. const type = this.getNodeType( builder );
  30643. const inputType = this.getInputType( builder );
  30644. const a = this.aNode;
  30645. const b = this.bNode;
  30646. const params = [];
  30647. if (
  30648. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  30649. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  30650. method === SubgroupFunctionNode.QUAD_BROADCAST
  30651. ) {
  30652. const bType = b.getNodeType( builder );
  30653. params.push(
  30654. a.build( builder, type ),
  30655. b.build( builder, bType === 'float' ? 'int' : type )
  30656. );
  30657. } else if (
  30658. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  30659. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  30660. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  30661. ) {
  30662. params.push(
  30663. a.build( builder, type ),
  30664. b.build( builder, 'uint' )
  30665. );
  30666. } else {
  30667. if ( a !== null ) params.push( a.build( builder, inputType ) );
  30668. if ( b !== null ) params.push( b.build( builder, inputType ) );
  30669. }
  30670. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  30671. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  30672. }
  30673. serialize( data ) {
  30674. super.serialize( data );
  30675. data.method = this.method;
  30676. }
  30677. deserialize( data ) {
  30678. super.deserialize( data );
  30679. this.method = data.method;
  30680. }
  30681. }
  30682. // 0 inputs
  30683. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  30684. // 1 input
  30685. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  30686. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  30687. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  30688. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  30689. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  30690. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  30691. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  30692. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  30693. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  30694. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  30695. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  30696. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  30697. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  30698. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  30699. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  30700. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  30701. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  30702. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  30703. // 2 inputs
  30704. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  30705. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  30706. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  30707. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  30708. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  30709. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  30710. /**
  30711. * Returns true if this invocation has the lowest subgroup_invocation_id
  30712. * among active invocations in the subgroup.
  30713. *
  30714. * @tsl
  30715. * @method
  30716. * @return {bool} The result of the computation.
  30717. */
  30718. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  30719. /**
  30720. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  30721. * is 1 if pred is true for that active invocation and 0 otherwise.
  30722. *
  30723. * @tsl
  30724. * @method
  30725. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  30726. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  30727. */
  30728. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  30729. /**
  30730. * A reduction that adds e among all active invocations and returns that result.
  30731. *
  30732. * @tsl
  30733. * @method
  30734. * @param {number} e - The value provided to the reduction by the current invocation.
  30735. * @return {number} The accumulated result of the reduction operation.
  30736. */
  30737. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  30738. /**
  30739. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  30740. *
  30741. * @tsl
  30742. * @method
  30743. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  30744. * @return {number} The accumulated result of the inclusive scan operation.
  30745. */
  30746. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  30747. /**
  30748. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  30749. *
  30750. * @tsl
  30751. * @method
  30752. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  30753. * @return {number} The accumulated result of the exclusive scan operation.
  30754. */
  30755. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  30756. /**
  30757. * A reduction that multiplies e among all active invocations and returns that result.
  30758. *
  30759. * @tsl
  30760. * @method
  30761. * @param {number} e - The value provided to the reduction by the current invocation.
  30762. * @return {number} The accumulated result of the reduction operation.
  30763. */
  30764. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  30765. /**
  30766. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  30767. *
  30768. * @tsl
  30769. * @method
  30770. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  30771. * @return {number} The accumulated result of the inclusive scan operation.
  30772. */
  30773. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  30774. /**
  30775. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  30776. *
  30777. * @tsl
  30778. * @method
  30779. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  30780. * @return {number} The accumulated result of the exclusive scan operation.
  30781. */
  30782. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  30783. /**
  30784. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  30785. *
  30786. * @tsl
  30787. * @method
  30788. * @param {number} e - The value provided to the reduction by the current invocation.
  30789. * @return {number} The result of the reduction operation.
  30790. */
  30791. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  30792. /**
  30793. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  30794. *
  30795. * @tsl
  30796. * @method
  30797. * @param {number} e - The value provided to the reduction by the current invocation.
  30798. * @return {number} The result of the reduction operation.
  30799. */
  30800. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  30801. /**
  30802. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  30803. *
  30804. * @tsl
  30805. * @method
  30806. * @param {number} e - The value provided to the reduction by the current invocation.
  30807. * @return {number} The result of the reduction operation.
  30808. */
  30809. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  30810. /**
  30811. * A reduction that performs a min of e among all active invocations and returns that result.
  30812. *
  30813. * @tsl
  30814. * @method
  30815. * @param {number} e - The value provided to the reduction by the current invocation.
  30816. * @return {number} The result of the reduction operation.
  30817. */
  30818. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  30819. /**
  30820. * A reduction that performs a max of e among all active invocations and returns that result.
  30821. *
  30822. * @tsl
  30823. * @method
  30824. * @param {number} e - The value provided to the reduction by the current invocation.
  30825. * @return {number} The result of the reduction operation.
  30826. */
  30827. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  30828. /**
  30829. * Returns true if e is true for all active invocations in the subgroup.
  30830. *
  30831. * @tsl
  30832. * @method
  30833. * @return {bool} The result of the computation.
  30834. */
  30835. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  30836. /**
  30837. * Returns true if e is true for any active invocation in the subgroup
  30838. *
  30839. * @tsl
  30840. * @method
  30841. * @return {bool} The result of the computation.
  30842. */
  30843. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  30844. /**
  30845. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  30846. *
  30847. * @tsl
  30848. * @method
  30849. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  30850. * @param {number} id - The subgroup invocation to broadcast from.
  30851. * @return {number} The broadcast value.
  30852. */
  30853. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  30854. /**
  30855. * Swaps e between invocations in the quad in the X direction.
  30856. *
  30857. * @tsl
  30858. * @method
  30859. * @param {number} e - The value to swap from the current invocation.
  30860. * @return {number} The value received from the swap operation.
  30861. */
  30862. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  30863. /**
  30864. * Swaps e between invocations in the quad in the Y direction.
  30865. *
  30866. * @tsl
  30867. * @method
  30868. * @param {number} e - The value to swap from the current invocation.
  30869. * @return {number} The value received from the swap operation.
  30870. */
  30871. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  30872. /**
  30873. * Swaps e between invocations in the quad diagonally.
  30874. *
  30875. * @tsl
  30876. * @method
  30877. * @param {number} e - The value to swap from the current invocation.
  30878. * @return {number} The value received from the swap operation.
  30879. */
  30880. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  30881. /**
  30882. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  30883. *
  30884. * @tsl
  30885. * @method
  30886. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  30887. * @param {number} id - The subgroup invocation to broadcast from.
  30888. * @return {number} The broadcast value.
  30889. */
  30890. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  30891. /**
  30892. * Returns v from the active invocation whose subgroup_invocation_id matches id
  30893. *
  30894. * @tsl
  30895. * @method
  30896. * @param {number} v - The value to return from subgroup invocation id^mask.
  30897. * @param {number} id - The subgroup invocation which returns the value v.
  30898. * @return {number} The broadcast value.
  30899. */
  30900. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  30901. /**
  30902. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  30903. *
  30904. * @tsl
  30905. * @method
  30906. * @param {number} v - The value to return from subgroup invocation id^mask.
  30907. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  30908. * @return {number} The broadcast value.
  30909. */
  30910. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  30911. /**
  30912. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  30913. *
  30914. * @tsl
  30915. * @method
  30916. * @param {number} v - The value to return from subgroup invocation id^mask.
  30917. * @param {number} delta - A value that offsets the current in.
  30918. * @return {number} The broadcast value.
  30919. */
  30920. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  30921. /**
  30922. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  30923. *
  30924. * @tsl
  30925. * @method
  30926. * @param {number} v - The value to return from subgroup invocation id^mask.
  30927. * @param {number} delta - A value that offsets the current subgroup invocation.
  30928. * @return {number} The broadcast value.
  30929. */
  30930. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  30931. /**
  30932. * Broadcasts e from the quad invocation with id equal to id.
  30933. *
  30934. * @tsl
  30935. * @method
  30936. * @param {number} e - The value to broadcast.
  30937. * @return {number} The broadcast value.
  30938. */
  30939. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  30940. let uniformsLib;
  30941. function getLightData( light ) {
  30942. uniformsLib = uniformsLib || new WeakMap();
  30943. let uniforms = uniformsLib.get( light );
  30944. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  30945. return uniforms;
  30946. }
  30947. /**
  30948. * TSL function for getting a shadow matrix uniform node for the given light.
  30949. *
  30950. * @tsl
  30951. * @function
  30952. * @param {Light} light -The light source.
  30953. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  30954. */
  30955. function lightShadowMatrix( light ) {
  30956. const data = getLightData( light );
  30957. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  30958. // normally, shadow matrices are updated in ShadowNode. However, if the shadow matrix is used outside
  30959. // of shadow rendering (like in ProjectorLightNode), the shadow matrix still requires an update
  30960. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  30961. if ( light.shadow.camera.coordinateSystem !== frame.camera.coordinateSystem ) {
  30962. light.shadow.camera.coordinateSystem = frame.camera.coordinateSystem;
  30963. light.shadow.camera.updateProjectionMatrix();
  30964. }
  30965. light.shadow.updateMatrices( light );
  30966. }
  30967. return light.shadow.matrix;
  30968. } ) );
  30969. }
  30970. /**
  30971. * TSL function for getting projected uv coordinates for the given light.
  30972. * Relevant when using maps with spot lights.
  30973. *
  30974. * @tsl
  30975. * @function
  30976. * @param {Light} light -The light source.
  30977. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  30978. * @returns {Node<vec3>} The projected uvs.
  30979. */
  30980. function lightProjectionUV( light, position = positionWorld ) {
  30981. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  30982. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  30983. return projectionUV;
  30984. }
  30985. /**
  30986. * TSL function for getting the position in world space for the given light.
  30987. *
  30988. * @tsl
  30989. * @function
  30990. * @param {Light} light -The light source.
  30991. * @returns {UniformNode<vec3>} The light's position in world space.
  30992. */
  30993. function lightPosition( light ) {
  30994. const data = getLightData( light );
  30995. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  30996. }
  30997. /**
  30998. * TSL function for getting the light target position in world space for the given light.
  30999. *
  31000. * @tsl
  31001. * @function
  31002. * @param {Light} light -The light source.
  31003. * @returns {UniformNode<vec3>} The light target position in world space.
  31004. */
  31005. function lightTargetPosition( light ) {
  31006. const data = getLightData( light );
  31007. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  31008. }
  31009. /**
  31010. * TSL function for getting the position in view space for the given light.
  31011. *
  31012. * @tsl
  31013. * @function
  31014. * @param {Light} light - The light source.
  31015. * @returns {UniformNode<vec3>} The light's position in view space.
  31016. */
  31017. function lightViewPosition( light ) {
  31018. const data = getLightData( light );
  31019. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  31020. self.value = self.value || new Vector3();
  31021. self.value.setFromMatrixPosition( light.matrixWorld );
  31022. self.value.applyMatrix4( camera.matrixWorldInverse );
  31023. } ) );
  31024. }
  31025. /**
  31026. * TSL function for getting the light target direction for the given light.
  31027. *
  31028. * @tsl
  31029. * @function
  31030. * @param {Light} light -The light source.
  31031. * @returns {Node<vec3>} The light's target direction.
  31032. */
  31033. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  31034. /**
  31035. * A node representing the total diffuse light.
  31036. *
  31037. * @type {Node<vec3>}
  31038. */
  31039. const totalDiffuse = property( 'vec3', 'totalDiffuse' );
  31040. /**
  31041. * A node representing the total specular light.
  31042. *
  31043. * @type {Node<vec3>}
  31044. */
  31045. const totalSpecular = property( 'vec3', 'totalSpecular' );
  31046. /**
  31047. * A node representing the outgoing light.
  31048. *
  31049. * @type {Node<vec3>}
  31050. */
  31051. const outgoingLight = property( 'vec3', 'outgoingLight' );
  31052. /**
  31053. * Sorts an array of lights in ascending order by their IDs.
  31054. *
  31055. * @private
  31056. * @param {Array<Light>} lights - The array of lights to sort.
  31057. * @return {Array<Light>} The sorted array of lights.
  31058. */
  31059. const sortLights = ( lights ) => {
  31060. return lights.sort( ( a, b ) => a.id - b.id );
  31061. };
  31062. /**
  31063. * Finds and returns a lighting node associated with a specific light ID.
  31064. *
  31065. * @private
  31066. * @param {number} id - The ID of the light to search for.
  31067. * @param {Array<LightingNode>} lightNodes - The array of lighting nodes to search within.
  31068. * @return {?LightingNode} The matching lighting node, or null if not found.
  31069. */
  31070. const getLightNodeById = ( id, lightNodes ) => {
  31071. for ( const lightNode of lightNodes ) {
  31072. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  31073. return lightNode;
  31074. }
  31075. }
  31076. return null;
  31077. };
  31078. /**
  31079. * WeakMap cache mapping light objects to their corresponding lighting node instances.
  31080. *
  31081. * @private
  31082. * @type {WeakMap<Light, LightingNode>}
  31083. */
  31084. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  31085. /**
  31086. * Array used to temporarily store light IDs and shadow casting states for hashing.
  31087. *
  31088. * @private
  31089. * @type {Array<number>}
  31090. */
  31091. const _hashData = [];
  31092. /**
  31093. * This node represents the scene's lighting and manages the lighting model's life cycle
  31094. * for the current build 3D object. It is responsible for computing the total outgoing
  31095. * light in a given lighting context.
  31096. *
  31097. * @augments Node
  31098. */
  31099. class LightsNode extends Node {
  31100. static get type() {
  31101. return 'LightsNode';
  31102. }
  31103. /**
  31104. * Constructs a new lights node.
  31105. */
  31106. constructor() {
  31107. super( 'vec3' );
  31108. /**
  31109. * A node representing the total diffuse light.
  31110. *
  31111. * @type {Node<vec3>}
  31112. */
  31113. this.totalDiffuseNode = totalDiffuse;
  31114. /**
  31115. * A node representing the total specular light.
  31116. *
  31117. * @type {Node<vec3>}
  31118. */
  31119. this.totalSpecularNode = totalSpecular;
  31120. /**
  31121. * A node representing the outgoing light.
  31122. *
  31123. * @type {Node<vec3>}
  31124. */
  31125. this.outgoingLightNode = outgoingLight;
  31126. /**
  31127. * An array representing the lights in the scene.
  31128. *
  31129. * @private
  31130. * @type {Array<Light>}
  31131. */
  31132. this._lights = [];
  31133. /**
  31134. * `LightsNode` sets this property to `true` by default.
  31135. *
  31136. * @type {boolean}
  31137. * @default true
  31138. */
  31139. this.global = true;
  31140. }
  31141. /**
  31142. * Overwrites the default {@link Node#customCacheKey} implementation by including
  31143. * light data into the cache key.
  31144. *
  31145. * @return {number} The custom cache key.
  31146. */
  31147. customCacheKey() {
  31148. const lights = this._lights;
  31149. for ( let i = 0; i < lights.length; i ++ ) {
  31150. const light = lights[ i ];
  31151. _hashData.push( light.id );
  31152. _hashData.push( light.castShadow ? 1 : 0 );
  31153. if ( light.isSpotLight === true ) {
  31154. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  31155. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  31156. _hashData.push( hashMap, hashColorNode );
  31157. }
  31158. }
  31159. const cacheKey = hashArray( _hashData );
  31160. _hashData.length = 0;
  31161. return cacheKey;
  31162. }
  31163. /**
  31164. * Computes a hash value for identifying the current light nodes setup.
  31165. *
  31166. * @param {NodeBuilder} builder - A reference to the current node builder.
  31167. * @return {string} The computed hash.
  31168. */
  31169. getHash( builder ) {
  31170. const nodeData = builder.getDataFromNode( this );
  31171. if ( nodeData.lightNodesHash === undefined ) {
  31172. const lightNodes = this.setupLightsNode( builder );
  31173. nodeData.lightNodes = lightNodes;
  31174. const hash = [];
  31175. for ( const lightNode of lightNodes ) {
  31176. hash.push( lightNode.getHash() );
  31177. }
  31178. nodeData.lightNodesHash = 'lights-' + hash.join( ',' );
  31179. }
  31180. return nodeData.lightNodesHash;
  31181. }
  31182. /**
  31183. * Analyzes the node's dependencies by building all nested light nodes
  31184. * and the output node.
  31185. *
  31186. * @param {NodeBuilder} builder - A reference to the current node builder.
  31187. */
  31188. analyze( builder ) {
  31189. const properties = builder.getNodeProperties( this );
  31190. for ( const node of properties.nodes ) {
  31191. node.build( builder );
  31192. }
  31193. properties.outputNode.build( builder );
  31194. }
  31195. /**
  31196. * Creates lighting nodes for each scene light. This makes it possible to further
  31197. * process lights in the node system.
  31198. *
  31199. * @param {NodeBuilder} builder - A reference to the current node builder.
  31200. * @return {Array<LightingNode>} The array of lighting nodes.
  31201. */
  31202. setupLightsNode( builder ) {
  31203. const nodeData = builder.getDataFromNode( this );
  31204. const lightNodes = [];
  31205. const previousLightNodes = nodeData.lightNodes || null;
  31206. const materialLightings = builder.context.materialLightings;
  31207. const lights = sortLights( [ ...materialLightings, ...this._lights ] );
  31208. const nodeLibrary = builder.renderer.library;
  31209. for ( const light of lights ) {
  31210. if ( light.isNode ) {
  31211. lightNodes.push( light );
  31212. } else {
  31213. let lightNode = null;
  31214. if ( previousLightNodes !== null ) {
  31215. lightNode = getLightNodeById( light.id, previousLightNodes );
  31216. }
  31217. if ( lightNode === null ) {
  31218. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  31219. if ( lightNodeClass === null ) {
  31220. warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  31221. continue;
  31222. }
  31223. if ( _lightsNodeRef.has( light ) === false ) {
  31224. _lightsNodeRef.set( light, new lightNodeClass( light ) );
  31225. }
  31226. lightNode = _lightsNodeRef.get( light );
  31227. }
  31228. lightNodes.push( lightNode );
  31229. }
  31230. }
  31231. return lightNodes;
  31232. }
  31233. /**
  31234. * Sets up a direct light in the lighting model.
  31235. *
  31236. * @param {Object} builder - The builder object containing the context and stack.
  31237. * @param {Object} lightNode - The light node.
  31238. * @param {Object} lightData - The light object containing color and direction properties.
  31239. */
  31240. setupDirectLight( builder, lightNode, lightData ) {
  31241. const { lightingModel, reflectedLight } = builder.context;
  31242. lightingModel.direct( {
  31243. ...lightData,
  31244. lightNode,
  31245. reflectedLight
  31246. }, builder );
  31247. }
  31248. /**
  31249. * Sets up a direct rect area light in the lighting model.
  31250. *
  31251. * @param {Object} builder - The builder object containing the context and stack.
  31252. * @param {Object} lightNode - The light node.
  31253. * @param {Object} lightData - The light object containing color and area light properties.
  31254. */
  31255. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  31256. const { lightingModel, reflectedLight } = builder.context;
  31257. lightingModel.directRectArea( {
  31258. ...lightData,
  31259. lightNode,
  31260. reflectedLight
  31261. }, builder );
  31262. }
  31263. /**
  31264. * Setups the internal lights by building all respective
  31265. * light nodes.
  31266. *
  31267. * @param {NodeBuilder} builder - A reference to the current node builder.
  31268. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  31269. */
  31270. setupLights( builder, lightNodes ) {
  31271. for ( const lightNode of lightNodes ) {
  31272. lightNode.build( builder );
  31273. }
  31274. }
  31275. getLightNodes( builder ) {
  31276. const nodeData = builder.getDataFromNode( this );
  31277. if ( nodeData.lightNodes === undefined ) {
  31278. nodeData.lightNodes = this.setupLightsNode( builder );
  31279. }
  31280. return nodeData.lightNodes;
  31281. }
  31282. /**
  31283. * The implementation makes sure that for each light in the scene
  31284. * there is a corresponding light node. By building the light nodes
  31285. * and evaluating the lighting model the outgoing light is computed.
  31286. *
  31287. * @param {NodeBuilder} builder - A reference to the current node builder.
  31288. * @return {Node<vec3>} A node representing the outgoing light.
  31289. */
  31290. setup( builder ) {
  31291. const currentLightsNode = builder.lightsNode;
  31292. builder.lightsNode = this;
  31293. let outgoingLightNode = this.outgoingLightNode;
  31294. const context = builder.context;
  31295. const lightingModel = context.lightingModel;
  31296. const properties = builder.getNodeProperties( this );
  31297. if ( lightingModel ) {
  31298. const { totalDiffuseNode, totalSpecularNode } = this;
  31299. context.outgoingLight = outgoingLightNode;
  31300. const stack = builder.addStack();
  31301. properties.nodes = stack.nodes;
  31302. lightingModel.start( builder );
  31303. const { backdrop, backdropAlpha } = context;
  31304. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  31305. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  31306. if ( backdrop !== null ) {
  31307. if ( backdropAlpha !== null ) {
  31308. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  31309. } else {
  31310. totalDiffuse = vec3( backdrop );
  31311. }
  31312. }
  31313. totalDiffuseNode.assign( totalDiffuse );
  31314. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  31315. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  31316. lightingModel.finish( builder );
  31317. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  31318. } else {
  31319. properties.nodes = [];
  31320. }
  31321. builder.lightsNode = currentLightsNode;
  31322. return outgoingLightNode;
  31323. }
  31324. /**
  31325. * Configures this node with an array of lights.
  31326. *
  31327. * @param {Array<Light>} lights - An array of lights.
  31328. * @return {LightsNode} A reference to this node.
  31329. */
  31330. setLights( lights ) {
  31331. this._lights = lights;
  31332. return this;
  31333. }
  31334. /**
  31335. * Returns an array of the scene's lights.
  31336. *
  31337. * @return {Array<Light>} The scene's lights.
  31338. */
  31339. getLights() {
  31340. return this._lights;
  31341. }
  31342. /**
  31343. * Whether the scene has lights or not.
  31344. *
  31345. * @type {boolean}
  31346. */
  31347. get hasLights() {
  31348. return this._lights.length > 0;
  31349. }
  31350. }
  31351. /**
  31352. * TSL function for creating an instance of `LightsNode` and configuring
  31353. * it with the given array of lights.
  31354. *
  31355. * @tsl
  31356. * @function
  31357. * @param {Array<Light>} lights - An array of lights.
  31358. * @return {LightsNode} The created lights node.
  31359. */
  31360. const lights = ( lights = [] ) => new LightsNode().setLights( lights );
  31361. /**
  31362. * Base class for all shadow nodes.
  31363. *
  31364. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  31365. * Lighting nodes might share the same shadow node type or use specific ones depending on
  31366. * their requirements.
  31367. *
  31368. * @augments Node
  31369. */
  31370. class ShadowBaseNode extends Node {
  31371. static get type() {
  31372. return 'ShadowBaseNode';
  31373. }
  31374. /**
  31375. * Constructs a new shadow base node.
  31376. *
  31377. * @param {Light} light - The shadow casting light.
  31378. */
  31379. constructor( light ) {
  31380. super();
  31381. /**
  31382. * The shadow casting light.
  31383. *
  31384. * @type {Light}
  31385. */
  31386. this.light = light;
  31387. /**
  31388. * Overwritten since shadows are updated by default per render.
  31389. *
  31390. * @type {string}
  31391. * @default 'render'
  31392. */
  31393. this.updateBeforeType = NodeUpdateType.RENDER;
  31394. /**
  31395. * This flag can be used for type testing.
  31396. *
  31397. * @type {boolean}
  31398. * @readonly
  31399. * @default true
  31400. */
  31401. this.isShadowBaseNode = true;
  31402. }
  31403. /**
  31404. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  31405. *
  31406. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  31407. */
  31408. setupShadowPosition( { context, material } ) {
  31409. // Use assign inside an Fn()
  31410. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  31411. }
  31412. }
  31413. /**
  31414. * TSL object that represents the vertex position in world space during the shadow pass.
  31415. *
  31416. * @tsl
  31417. * @type {Node<vec3>}
  31418. */
  31419. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  31420. /**
  31421. * Saves the state of the given renderer and stores it into the given state object.
  31422. *
  31423. * If not state object is provided, the function creates one.
  31424. *
  31425. * @private
  31426. * @function
  31427. * @param {Renderer} renderer - The renderer.
  31428. * @param {Object} [state={}] - The state.
  31429. * @return {Object} The state.
  31430. */
  31431. function saveRendererState( renderer, state = {} ) {
  31432. state.toneMapping = renderer.toneMapping;
  31433. state.toneMappingExposure = renderer.toneMappingExposure;
  31434. state.outputColorSpace = renderer.outputColorSpace;
  31435. state.renderTarget = renderer.getRenderTarget();
  31436. state.activeCubeFace = renderer.getActiveCubeFace();
  31437. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  31438. state.renderObjectFunction = renderer.getRenderObjectFunction();
  31439. state.pixelRatio = renderer.getPixelRatio();
  31440. state.mrt = renderer.getMRT();
  31441. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  31442. state.clearAlpha = renderer.getClearAlpha();
  31443. state.autoClear = renderer.autoClear;
  31444. state.scissorTest = renderer.getScissorTest();
  31445. return state;
  31446. }
  31447. /**
  31448. * Saves the state of the given renderer and stores it into the given state object.
  31449. * Besides, the function also resets the state of the renderer to its default values.
  31450. *
  31451. * If not state object is provided, the function creates one.
  31452. *
  31453. * @private
  31454. * @function
  31455. * @param {Renderer} renderer - The renderer.
  31456. * @param {Object} [state={}] - The state.
  31457. * @return {Object} The state.
  31458. */
  31459. function resetRendererState( renderer, state ) {
  31460. state = saveRendererState( renderer, state );
  31461. renderer.setMRT( null );
  31462. renderer.setRenderObjectFunction( null );
  31463. renderer.setClearColor( 0x000000, 1 );
  31464. renderer.autoClear = true;
  31465. return state;
  31466. }
  31467. /**
  31468. * Restores the state of the given renderer from the given state object.
  31469. *
  31470. * @private
  31471. * @function
  31472. * @param {Renderer} renderer - The renderer.
  31473. * @param {Object} state - The state to restore.
  31474. */
  31475. function restoreRendererState( renderer, state ) {
  31476. renderer.toneMapping = state.toneMapping;
  31477. renderer.toneMappingExposure = state.toneMappingExposure;
  31478. renderer.outputColorSpace = state.outputColorSpace;
  31479. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  31480. renderer.setRenderObjectFunction( state.renderObjectFunction );
  31481. renderer.setPixelRatio( state.pixelRatio );
  31482. renderer.setMRT( state.mrt );
  31483. renderer.setClearColor( state.clearColor, state.clearAlpha );
  31484. renderer.autoClear = state.autoClear;
  31485. renderer.setScissorTest( state.scissorTest );
  31486. }
  31487. /**
  31488. * Saves the state of the given scene and stores it into the given state object.
  31489. *
  31490. * If not state object is provided, the function creates one.
  31491. *
  31492. * @private
  31493. * @function
  31494. * @param {Scene} scene - The scene.
  31495. * @param {Object} [state={}] - The state.
  31496. * @return {Object} The state.
  31497. */
  31498. function saveSceneState( scene, state = {} ) {
  31499. state.background = scene.background;
  31500. state.backgroundNode = scene.backgroundNode;
  31501. state.overrideMaterial = scene.overrideMaterial;
  31502. return state;
  31503. }
  31504. /**
  31505. * Saves the state of the given scene and stores it into the given state object.
  31506. * Besides, the function also resets the state of the scene to its default values.
  31507. *
  31508. * If not state object is provided, the function creates one.
  31509. *
  31510. * @private
  31511. * @function
  31512. * @param {Scene} scene - The scene.
  31513. * @param {Object} [state={}] - The state.
  31514. * @return {Object} The state.
  31515. */
  31516. function resetSceneState( scene, state ) {
  31517. state = saveSceneState( scene, state );
  31518. scene.background = null;
  31519. scene.backgroundNode = null;
  31520. scene.overrideMaterial = null;
  31521. return state;
  31522. }
  31523. /**
  31524. * Restores the state of the given scene from the given state object.
  31525. *
  31526. * @private
  31527. * @function
  31528. * @param {Scene} scene - The scene.
  31529. * @param {Object} state - The state to restore.
  31530. */
  31531. function restoreSceneState( scene, state ) {
  31532. scene.background = state.background;
  31533. scene.backgroundNode = state.backgroundNode;
  31534. scene.overrideMaterial = state.overrideMaterial;
  31535. }
  31536. /**
  31537. * Saves the state of the given renderer and scene and stores it into the given state object.
  31538. *
  31539. * If not state object is provided, the function creates one.
  31540. *
  31541. * @private
  31542. * @function
  31543. * @param {Renderer} renderer - The renderer.
  31544. * @param {Scene} scene - The scene.
  31545. * @param {Object} [state={}] - The state.
  31546. * @return {Object} The state.
  31547. */
  31548. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  31549. state = saveRendererState( renderer, state );
  31550. state = saveSceneState( scene, state );
  31551. return state;
  31552. }
  31553. /**
  31554. * Saves the state of the given renderer and scene and stores it into the given state object.
  31555. * Besides, the function also resets the state of the renderer and scene to its default values.
  31556. *
  31557. * If not state object is provided, the function creates one.
  31558. *
  31559. * @private
  31560. * @function
  31561. * @param {Renderer} renderer - The renderer.
  31562. * @param {Scene} scene - The scene.
  31563. * @param {Object} [state={}] - The state.
  31564. * @return {Object} The state.
  31565. */
  31566. function resetRendererAndSceneState( renderer, scene, state ) {
  31567. state = resetRendererState( renderer, state );
  31568. state = resetSceneState( scene, state );
  31569. return state;
  31570. }
  31571. /**
  31572. * Restores the state of the given renderer and scene from the given state object.
  31573. *
  31574. * @private
  31575. * @function
  31576. * @param {Renderer} renderer - The renderer.
  31577. * @param {Scene} scene - The scene.
  31578. * @param {Object} state - The state to restore.
  31579. */
  31580. function restoreRendererAndSceneState( renderer, scene, state ) {
  31581. restoreRendererState( renderer, state );
  31582. restoreSceneState( scene, state );
  31583. }
  31584. var RendererUtils = /*#__PURE__*/Object.freeze({
  31585. __proto__: null,
  31586. resetRendererAndSceneState: resetRendererAndSceneState,
  31587. resetRendererState: resetRendererState,
  31588. resetSceneState: resetSceneState,
  31589. restoreRendererAndSceneState: restoreRendererAndSceneState,
  31590. restoreRendererState: restoreRendererState,
  31591. restoreSceneState: restoreSceneState,
  31592. saveRendererAndSceneState: saveRendererAndSceneState,
  31593. saveRendererState: saveRendererState,
  31594. saveSceneState: saveSceneState
  31595. });
  31596. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  31597. /**
  31598. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  31599. * with a binary `[0,1]` result.
  31600. *
  31601. * @method
  31602. * @param {Object} inputs - The input parameter object.
  31603. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31604. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  31605. * @return {Node<float>} The filtering result.
  31606. */
  31607. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  31608. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  31609. if ( depthTexture.isArrayTexture ) {
  31610. basic = basic.depth( depthLayer );
  31611. }
  31612. return basic.compare( shadowCoord.z );
  31613. } );
  31614. /**
  31615. * A shadow filtering function performing PCF filtering with Vogel disk sampling and IGN.
  31616. *
  31617. * Uses 5 samples distributed via Vogel disk pattern, rotated per-pixel using Interleaved
  31618. * Gradient Noise (IGN) to break up banding artifacts. Combined with hardware PCF (4-tap
  31619. * filtering per sample), this effectively provides 20 filtered taps with better distribution.
  31620. *
  31621. * @method
  31622. * @param {Object} inputs - The input parameter object.
  31623. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31624. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  31625. * @param {LightShadow} inputs.shadow - The light shadow.
  31626. * @return {Node<float>} The filtering result.
  31627. */
  31628. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  31629. const depthCompare = ( uv, compare ) => {
  31630. let depth = texture( depthTexture, uv );
  31631. if ( depthTexture.isArrayTexture ) {
  31632. depth = depth.depth( depthLayer );
  31633. }
  31634. return depth.compare( compare );
  31635. };
  31636. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31637. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31638. const texelSize = vec2( 1 ).div( mapSize );
  31639. const radiusScaled = radius.mul( texelSize.x );
  31640. // Use IGN to rotate sampling pattern per pixel (phi = IGN * 2π)
  31641. const phi = interleavedGradientNoise( screenCoordinate.xy ).mul( 6.28318530718 );
  31642. // 5 samples using Vogel disk distribution
  31643. return add(
  31644. depthCompare( shadowCoord.xy.add( vogelDiskSample( 0, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  31645. depthCompare( shadowCoord.xy.add( vogelDiskSample( 1, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  31646. depthCompare( shadowCoord.xy.add( vogelDiskSample( 2, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  31647. depthCompare( shadowCoord.xy.add( vogelDiskSample( 3, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  31648. depthCompare( shadowCoord.xy.add( vogelDiskSample( 4, 5, phi ).mul( radiusScaled ) ), shadowCoord.z )
  31649. ).mul( 1 / 5 );
  31650. } );
  31651. /**
  31652. * A shadow filtering function performing PCF soft filtering.
  31653. *
  31654. * @method
  31655. * @param {Object} inputs - The input parameter object.
  31656. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31657. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  31658. * @param {LightShadow} inputs.shadow - The light shadow.
  31659. * @return {Node<float>} The filtering result.
  31660. */
  31661. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  31662. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31663. const texelSize = vec2( 1 ).div( mapSize );
  31664. const uv = shadowCoord.xy;
  31665. const f = fract( uv.mul( mapSize ).add( 0.5 ) ).toConst();
  31666. uv.subAssign( f.sub( 0.5 ).mul( texelSize ) );
  31667. const gatherCompare = ( offset ) => {
  31668. let t = texture( depthTexture, uv ).offset( offset ).gather();
  31669. if ( depthTexture.isArrayTexture ) {
  31670. t = t.depth( depthLayer );
  31671. }
  31672. return t.compare( shadowCoord.z );
  31673. };
  31674. const c1 = gatherCompare( ivec2( -1, 1 ) ).toConst();
  31675. const c2 = gatherCompare( ivec2( 1, 1 ) ).toConst();
  31676. const c3 = gatherCompare( ivec2( -1, -1 ) ).toConst();
  31677. const c4 = gatherCompare( ivec2( 1, -1 ) ).toConst();
  31678. return add(
  31679. mix( c1.x, c2.y, f.x ).add( c1.y ).add( c2.x ).mul( f.y ),
  31680. mix( c1.w, c2.z, f.x ).add( c1.z ).add( c2.w ),
  31681. mix( c3.x, c4.y, f.x ).add( c3.y ).add( c4.x ),
  31682. mix( c3.w, c4.z, f.x ).add( c3.z ).add( c4.w ).mul( f.y.oneMinus() )
  31683. ).mul( 1 / 9 );
  31684. } );
  31685. /**
  31686. * A shadow filtering function performing VSM filtering.
  31687. *
  31688. * @method
  31689. * @param {Object} inputs - The input parameter object.
  31690. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31691. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  31692. * @return {Node<float>} The filtering result.
  31693. */
  31694. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer }, builder ) => {
  31695. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  31696. if ( depthTexture.isArrayTexture ) {
  31697. distribution = distribution.depth( depthLayer );
  31698. }
  31699. distribution = distribution.rg;
  31700. const mean = distribution.x;
  31701. const variance = max$1( 0.0000001, distribution.y.mul( distribution.y ) );
  31702. const hardShadow = ( builder.renderer.reversedDepthBuffer ) ? step( mean, shadowCoord.z ) : step( shadowCoord.z, mean );
  31703. const output = float( 1 ).toVar(); // default, fully lit
  31704. If( hardShadow.notEqual( 1.0 ), () => {
  31705. // Distance from mean
  31706. const d = shadowCoord.z.sub( mean );
  31707. // Chebyshev's inequality for upper bound on probability
  31708. let p_max = variance.div( variance.add( d.mul( d ) ) );
  31709. // Reduce light bleeding by remapping [amount, 1] to [0, 1]
  31710. p_max = clamp( sub( p_max, 0.3 ).div( 0.65 ) );
  31711. output.assign( max$1( hardShadow, p_max ) );
  31712. } );
  31713. return output;
  31714. } );
  31715. /**
  31716. * Retrieves or creates a shadow material for the given light source.
  31717. *
  31718. * This function checks if a shadow material already exists for the provided light.
  31719. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  31720. * in the `shadowMaterialLib` for future use.
  31721. *
  31722. * @tsl
  31723. * @function
  31724. * @param {Light} light - The light source for which the shadow material is needed.
  31725. * If the light is a point light, a depth node is calculated
  31726. * using the linear shadow distance.
  31727. * @returns {NodeMaterial} The shadow material associated with the given light.
  31728. */
  31729. const getShadowMaterial = ( light ) => {
  31730. let material = shadowMaterialLib.get( light );
  31731. if ( material === undefined ) {
  31732. material = new NodeMaterial();
  31733. material.colorNode = vec4( 0, 0, 0, 1 );
  31734. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  31735. material.name = 'ShadowMaterial';
  31736. material.blending = NoBlending;
  31737. material.fog = false;
  31738. shadowMaterialLib.set( light, material );
  31739. }
  31740. return material;
  31741. };
  31742. /**
  31743. * Disposes the shadow material for the given light source.
  31744. *
  31745. * @param {Light} light - The light source.
  31746. */
  31747. const disposeShadowMaterial = ( light ) => {
  31748. const material = shadowMaterialLib.get( light );
  31749. if ( material !== undefined ) {
  31750. material.dispose();
  31751. shadowMaterialLib.delete( light );
  31752. }
  31753. };
  31754. //
  31755. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  31756. const _shadowRenderObjectKeys = [];
  31757. /**
  31758. * Creates a function to render shadow objects in a scene.
  31759. *
  31760. * @tsl
  31761. * @function
  31762. * @param {Renderer} renderer - The renderer.
  31763. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  31764. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  31765. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  31766. * @return {shadowRenderObjectFunction} A function that renders shadow objects.
  31767. */
  31768. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  31769. _shadowRenderObjectKeys[ 0 ] = renderer;
  31770. _shadowRenderObjectKeys[ 1 ] = shadow;
  31771. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  31772. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  31773. renderObjectFunction = ( object, scene, _camera, geometry, material, group, lightsNode, clippingContext, passId ) => {
  31774. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  31775. if ( useVelocity ) {
  31776. getDataFromObject( object ).useVelocity = true;
  31777. }
  31778. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  31779. renderer.renderObject( object, scene, _camera, geometry, material, group, lightsNode, clippingContext, passId );
  31780. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  31781. }
  31782. };
  31783. renderObjectFunction.shadowType = shadowType;
  31784. renderObjectFunction.useVelocity = useVelocity;
  31785. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  31786. }
  31787. _shadowRenderObjectKeys[ 0 ] = null;
  31788. _shadowRenderObjectKeys[ 1 ] = null;
  31789. return renderObjectFunction;
  31790. };
  31791. /**
  31792. * Represents the shader code for the first VSM render pass.
  31793. *
  31794. * @private
  31795. * @method
  31796. * @param {Object} inputs - The input parameter object.
  31797. * @param {Node<float>} inputs.samples - The number of samples
  31798. * @param {Node<float>} inputs.radius - The radius.
  31799. * @param {Node<float>} inputs.size - The size.
  31800. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  31801. * @return {Node<vec2>} The VSM output.
  31802. */
  31803. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  31804. const mean = float( 0 ).toVar( 'meanVertical' );
  31805. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  31806. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  31807. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  31808. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  31809. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  31810. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  31811. if ( shadowPass.value.isArrayTexture ) {
  31812. depth = depth.depth( depthLayer );
  31813. }
  31814. depth = depth.x;
  31815. mean.addAssign( depth );
  31816. squaredMean.addAssign( depth.mul( depth ) );
  31817. } );
  31818. mean.divAssign( samples );
  31819. squaredMean.divAssign( samples );
  31820. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  31821. return vec2( mean, std_dev );
  31822. } );
  31823. /**
  31824. * Represents the shader code for the second VSM render pass.
  31825. *
  31826. * @private
  31827. * @method
  31828. * @param {Object} inputs - The input parameter object.
  31829. * @param {Node<float>} inputs.samples - The number of samples
  31830. * @param {Node<float>} inputs.radius - The radius.
  31831. * @param {Node<float>} inputs.size - The size.
  31832. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  31833. * @return {Node<vec2>} The VSM output.
  31834. */
  31835. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  31836. const mean = float( 0 ).toVar( 'meanHorizontal' );
  31837. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  31838. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  31839. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  31840. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  31841. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  31842. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  31843. if ( shadowPass.value.isArrayTexture ) {
  31844. distribution = distribution.depth( depthLayer );
  31845. }
  31846. mean.addAssign( distribution.x );
  31847. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  31848. } );
  31849. mean.divAssign( samples );
  31850. squaredMean.divAssign( samples );
  31851. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  31852. return vec2( mean, std_dev );
  31853. } );
  31854. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  31855. //
  31856. let _rendererState;
  31857. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  31858. /**
  31859. * Represents the default shadow implementation for lighting nodes.
  31860. *
  31861. * @augments ShadowBaseNode
  31862. */
  31863. class ShadowNode extends ShadowBaseNode {
  31864. static get type() {
  31865. return 'ShadowNode';
  31866. }
  31867. /**
  31868. * Constructs a new shadow node.
  31869. *
  31870. * @param {Light} light - The shadow casting light.
  31871. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  31872. */
  31873. constructor( light, shadow = null ) {
  31874. super( light );
  31875. /**
  31876. * The light shadow which defines the properties light's
  31877. * shadow.
  31878. *
  31879. * @type {?LightShadow}
  31880. * @default null
  31881. */
  31882. this.shadow = shadow || light.shadow;
  31883. /**
  31884. * A reference to the shadow map which is a render target.
  31885. *
  31886. * @type {?RenderTarget}
  31887. * @default null
  31888. */
  31889. this.shadowMap = null;
  31890. /**
  31891. * Only relevant for VSM shadows. Render target for the
  31892. * first VSM render pass.
  31893. *
  31894. * @type {?RenderTarget}
  31895. * @default null
  31896. */
  31897. this.vsmShadowMapVertical = null;
  31898. /**
  31899. * Only relevant for VSM shadows. Render target for the
  31900. * second VSM render pass.
  31901. *
  31902. * @type {?RenderTarget}
  31903. * @default null
  31904. */
  31905. this.vsmShadowMapHorizontal = null;
  31906. /**
  31907. * Only relevant for VSM shadows. Node material which
  31908. * is used to render the first VSM pass.
  31909. *
  31910. * @type {?NodeMaterial}
  31911. * @default null
  31912. */
  31913. this.vsmMaterialVertical = null;
  31914. /**
  31915. * Only relevant for VSM shadows. Node material which
  31916. * is used to render the second VSM pass.
  31917. *
  31918. * @type {?NodeMaterial}
  31919. * @default null
  31920. */
  31921. this.vsmMaterialHorizontal = null;
  31922. /**
  31923. * A reference to the output node which defines the
  31924. * final result of this shadow node.
  31925. *
  31926. * @type {?Node}
  31927. * @private
  31928. * @default null
  31929. */
  31930. this._node = null;
  31931. /**
  31932. * The current shadow map type of this shadow node.
  31933. *
  31934. * @type {?number}
  31935. * @private
  31936. * @default null
  31937. */
  31938. this._currentShadowType = null;
  31939. /**
  31940. * A Weak Map holding the current frame ID per camera. Used
  31941. * to control the update of shadow maps.
  31942. *
  31943. * @type {WeakMap<Camera,number>}
  31944. * @private
  31945. */
  31946. this._cameraFrameId = new WeakMap();
  31947. /**
  31948. * This flag can be used for type testing.
  31949. *
  31950. * @type {boolean}
  31951. * @readonly
  31952. * @default true
  31953. */
  31954. this.isShadowNode = true;
  31955. /**
  31956. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  31957. *
  31958. * @type {number}
  31959. * @readonly
  31960. * @default true
  31961. */
  31962. this.depthLayer = 0;
  31963. }
  31964. /**
  31965. * Setups the shadow filtering.
  31966. *
  31967. * @param {NodeBuilder} builder - A reference to the current node builder.
  31968. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  31969. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  31970. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31971. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  31972. * @param {LightShadow} inputs.shadow - The light shadow.
  31973. * @return {Node<float>} The result node of the shadow filtering.
  31974. */
  31975. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  31976. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  31977. .and( shadowCoord.x.lessThanEqual( 1 ) )
  31978. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  31979. .and( shadowCoord.y.lessThanEqual( 1 ) )
  31980. .and( shadowCoord.z.lessThanEqual( 1 ) );
  31981. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  31982. return frustumTest.select( shadowNode, float( 1 ) );
  31983. }
  31984. /**
  31985. * Setups the shadow coordinates.
  31986. *
  31987. * @param {NodeBuilder} builder - A reference to the current node builder.
  31988. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  31989. * @return {Node<vec3>} The shadow coordinates.
  31990. */
  31991. setupShadowCoord( builder, shadowPosition ) {
  31992. const { shadow } = this;
  31993. const { renderer } = builder;
  31994. const bias = shadow.biasNode || reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  31995. let shadowCoord = shadowPosition;
  31996. let coordZ;
  31997. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  31998. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  31999. coordZ = shadowCoord.z;
  32000. } else {
  32001. const w = shadowCoord.w;
  32002. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  32003. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  32004. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  32005. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  32006. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  32007. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  32008. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  32009. }
  32010. shadowCoord = vec3(
  32011. shadowCoord.x,
  32012. shadowCoord.y.oneMinus(), // follow webgpu standards
  32013. renderer.reversedDepthBuffer ? coordZ.sub( bias ) : coordZ.add( bias )
  32014. );
  32015. return shadowCoord;
  32016. }
  32017. /**
  32018. * Returns the shadow filtering function for the given shadow type.
  32019. *
  32020. * @param {number} type - The shadow type.
  32021. * @return {Function} The filtering function.
  32022. */
  32023. getShadowFilterFn( type ) {
  32024. return _shadowFilterLib[ type ];
  32025. }
  32026. setupRenderTarget( shadow, builder ) {
  32027. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  32028. depthTexture.name = 'ShadowDepthTexture';
  32029. depthTexture.compareFunction = builder.renderer.reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare;
  32030. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  32031. shadowMap.texture.name = 'ShadowMap';
  32032. shadowMap.texture.type = shadow.mapType;
  32033. shadowMap.depthTexture = depthTexture;
  32034. return { shadowMap, depthTexture };
  32035. }
  32036. /**
  32037. * Setups the shadow output node.
  32038. *
  32039. * @param {NodeBuilder} builder - A reference to the current node builder.
  32040. * @return {Node<vec3>} The shadow output node.
  32041. */
  32042. setupShadow( builder ) {
  32043. const { renderer, camera } = builder;
  32044. const { light, shadow } = this;
  32045. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  32046. const shadowMapType = renderer.shadowMap.type;
  32047. const hasTextureCompare = renderer.hasCompatibility( Compatibility.TEXTURE_COMPARE );
  32048. if ( ( shadowMapType === PCFShadowMap || shadowMapType === PCFSoftShadowMap ) && hasTextureCompare ) {
  32049. depthTexture.minFilter = LinearFilter;
  32050. depthTexture.magFilter = LinearFilter;
  32051. } else {
  32052. depthTexture.minFilter = NearestFilter;
  32053. depthTexture.magFilter = NearestFilter;
  32054. }
  32055. shadow.camera.coordinateSystem = camera.coordinateSystem;
  32056. shadow.camera.updateProjectionMatrix();
  32057. // VSM
  32058. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  32059. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  32060. if ( shadowMap.depth > 1 ) {
  32061. if ( ! shadowMap._vsmShadowMapVertical ) {
  32062. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  32063. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  32064. }
  32065. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  32066. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  32067. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  32068. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  32069. }
  32070. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  32071. } else {
  32072. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  32073. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  32074. }
  32075. let shadowPassVertical = texture( depthTexture );
  32076. if ( depthTexture.isArrayTexture ) {
  32077. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  32078. }
  32079. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  32080. if ( depthTexture.isArrayTexture ) {
  32081. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  32082. }
  32083. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  32084. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  32085. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  32086. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  32087. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  32088. material.name = 'VSMVertical';
  32089. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  32090. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  32091. material.name = 'VSMHorizontal';
  32092. }
  32093. //
  32094. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  32095. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  32096. const shadowMatrix = lightShadowMatrix( light );
  32097. const shadowNormalBias = normalWorld.mul( normalBias );
  32098. let shadowPosition;
  32099. if ( ! renderer.highPrecision || builder.material.receivedShadowPositionNode || builder.context.shadowPositionWorld ) {
  32100. shadowPosition = shadowMatrix.mul( shadowPositionWorld.add( shadowNormalBias ) );
  32101. } else {
  32102. const highpShadowModelMatrix = uniform( 'mat4' ).onObjectUpdate( ( { object }, self ) => {
  32103. return self.value.multiplyMatrices( shadowMatrix.value, object.matrixWorld );
  32104. } );
  32105. shadowPosition = highpShadowModelMatrix.mul( positionLocal ).add( shadowMatrix.mul( vec4( shadowNormalBias, 0 ) ) );
  32106. }
  32107. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  32108. //
  32109. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  32110. if ( filterFn === null ) {
  32111. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  32112. }
  32113. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  32114. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  32115. let shadowColor;
  32116. if ( renderer.shadowMap.transmitted === true ) {
  32117. if ( shadowMap.texture.isCubeTexture ) {
  32118. // For cube shadow maps (point lights), use cubeTexture with vec3 coordinates
  32119. shadowColor = cubeTexture( shadowMap.texture, shadowCoord.xyz );
  32120. } else {
  32121. shadowColor = texture( shadowMap.texture, shadowCoord );
  32122. if ( depthTexture.isArrayTexture ) {
  32123. shadowColor = shadowColor.depth( this.depthLayer );
  32124. }
  32125. }
  32126. }
  32127. //
  32128. let shadowOutput;
  32129. if ( shadowColor ) {
  32130. shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  32131. } else {
  32132. shadowOutput = mix( 1, shadowNode, shadowIntensity ).toVar();
  32133. }
  32134. this.shadowMap = shadowMap;
  32135. this.shadow.map = shadowMap;
  32136. // Shadow Output + Inspector
  32137. const inspectName = `${ this.light.type } Shadow [ ${ this.light.name || 'ID: ' + this.light.id } ]`;
  32138. if ( shadowColor ) {
  32139. shadowOutput.toInspector( `${ inspectName } / Color`, () => {
  32140. if ( this.shadowMap.texture.isCubeTexture ) {
  32141. return cubeTexture( this.shadowMap.texture, equirectDirection() );
  32142. }
  32143. return texture( this.shadowMap.texture );
  32144. } );
  32145. }
  32146. return shadowOutput.toInspector( `${ inspectName } / Depth`, () => {
  32147. const shadowCameraNear = reference( 'near', 'float', this.shadow.camera );
  32148. const shadowCameraFar = reference( 'far', 'float', this.shadow.camera );
  32149. let depthNode;
  32150. if ( this.shadowMap.texture.isCubeTexture ) {
  32151. depthNode = cubeTexture( this.shadowMap.depthTexture, equirectDirection() ).r;
  32152. } else {
  32153. depthNode = texture( this.shadowMap.depthTexture ).r;
  32154. }
  32155. let linearDepth;
  32156. if ( this.shadow.camera.isPerspectiveCamera ) {
  32157. linearDepth = perspectiveDepthToViewZ( depthNode, shadowCameraNear, shadowCameraFar );
  32158. } else {
  32159. linearDepth = orthographicDepthToViewZ( depthNode, shadowCameraNear, shadowCameraFar );
  32160. }
  32161. linearDepth = viewZToOrthographicDepth( linearDepth, shadowCameraNear, shadowCameraFar );
  32162. return linearDepth.oneMinus();
  32163. } );
  32164. }
  32165. /**
  32166. * The implementation performs the setup of the output node. An output is only
  32167. * produces if shadow mapping is globally enabled in the renderer.
  32168. *
  32169. * @param {NodeBuilder} builder - A reference to the current node builder.
  32170. * @return {ShaderCallNodeInternal} The output node.
  32171. */
  32172. setup( builder ) {
  32173. if ( builder.renderer.shadowMap.enabled === false ) return;
  32174. return Fn( () => {
  32175. const currentShadowType = builder.renderer.shadowMap.type;
  32176. if ( this._currentShadowType !== currentShadowType ) {
  32177. this._reset();
  32178. this._node = null;
  32179. }
  32180. let node = this._node;
  32181. this.setupShadowPosition( builder );
  32182. if ( node === null ) {
  32183. this._node = node = this.setupShadow( builder );
  32184. this._currentShadowType = currentShadowType;
  32185. }
  32186. if ( builder.material.receivedShadowNode ) {
  32187. node = builder.material.receivedShadowNode( node );
  32188. }
  32189. return node;
  32190. } )();
  32191. }
  32192. /**
  32193. * Renders the shadow. The logic of this function could be included
  32194. * into {@link ShadowNode#updateShadow} however more specialized shadow
  32195. * nodes might require a custom shadow map rendering. By having a
  32196. * dedicated method, it's easier to overwrite the default behavior.
  32197. *
  32198. * @param {NodeFrame} frame - A reference to the current node frame.
  32199. */
  32200. renderShadow( frame ) {
  32201. const { shadow, shadowMap, light } = this;
  32202. const { renderer, scene } = frame;
  32203. shadow.updateMatrices( light );
  32204. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  32205. const currentSceneName = scene.name;
  32206. scene.name = `Shadow Map [ ${ light.name || 'ID: ' + light.id } ]`;
  32207. renderer.render( scene, shadow.camera );
  32208. scene.name = currentSceneName;
  32209. }
  32210. /**
  32211. * Updates the shadow.
  32212. *
  32213. * @param {NodeFrame} frame - A reference to the current node frame.
  32214. */
  32215. updateShadow( frame ) {
  32216. const { shadowMap, light, shadow } = this;
  32217. const { renderer, scene, camera } = frame;
  32218. const shadowType = renderer.shadowMap.type;
  32219. const depthVersion = shadowMap.depthTexture.version;
  32220. this._depthVersionCached = depthVersion;
  32221. const _shadowCameraLayer = shadow.camera.layers.mask;
  32222. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  32223. shadow.camera.layers.mask = camera.layers.mask;
  32224. }
  32225. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  32226. const currentMRT = renderer.getMRT();
  32227. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  32228. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  32229. scene.overrideMaterial = getShadowMaterial( light );
  32230. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  32231. renderer.setClearColor( 0x000000, 0 );
  32232. renderer.setRenderTarget( shadowMap );
  32233. this.renderShadow( frame );
  32234. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  32235. // vsm blur pass
  32236. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  32237. this.vsmPass( renderer );
  32238. }
  32239. shadow.camera.layers.mask = _shadowCameraLayer;
  32240. restoreRendererAndSceneState( renderer, scene, _rendererState );
  32241. }
  32242. /**
  32243. * For VSM additional render passes are required.
  32244. *
  32245. * @param {Renderer} renderer - A reference to the current renderer.
  32246. */
  32247. vsmPass( renderer ) {
  32248. const { shadow } = this;
  32249. const depth = this.shadowMap.depth;
  32250. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  32251. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  32252. renderer.setRenderTarget( this.vsmShadowMapVertical );
  32253. _quadMesh.material = this.vsmMaterialVertical;
  32254. _quadMesh.render( renderer );
  32255. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  32256. _quadMesh.material = this.vsmMaterialHorizontal;
  32257. _quadMesh.render( renderer );
  32258. }
  32259. /**
  32260. * Frees the internal resources of this shadow node.
  32261. */
  32262. dispose() {
  32263. this._reset();
  32264. super.dispose();
  32265. }
  32266. /**
  32267. * Resets the resouce state of this shadow node.
  32268. *
  32269. * @private
  32270. */
  32271. _reset() {
  32272. this._currentShadowType = null;
  32273. disposeShadowMaterial( this.light );
  32274. if ( this.shadowMap ) {
  32275. this.shadowMap.dispose();
  32276. this.shadowMap = null;
  32277. }
  32278. if ( this.vsmShadowMapVertical !== null ) {
  32279. this.vsmShadowMapVertical.dispose();
  32280. this.vsmShadowMapVertical = null;
  32281. this.vsmMaterialVertical.dispose();
  32282. this.vsmMaterialVertical = null;
  32283. }
  32284. if ( this.vsmShadowMapHorizontal !== null ) {
  32285. this.vsmShadowMapHorizontal.dispose();
  32286. this.vsmShadowMapHorizontal = null;
  32287. this.vsmMaterialHorizontal.dispose();
  32288. this.vsmMaterialHorizontal = null;
  32289. }
  32290. }
  32291. /**
  32292. * The implementation performs the update of the shadow map if necessary.
  32293. *
  32294. * @param {NodeFrame} frame - A reference to the current node frame.
  32295. */
  32296. updateBefore( frame ) {
  32297. const { shadow } = this;
  32298. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  32299. if ( needsUpdate ) {
  32300. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  32301. needsUpdate = false;
  32302. }
  32303. this._cameraFrameId[ frame.camera ] = frame.frameId;
  32304. }
  32305. if ( needsUpdate ) {
  32306. this.updateShadow( frame );
  32307. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  32308. shadow.needsUpdate = false;
  32309. }
  32310. }
  32311. }
  32312. }
  32313. /**
  32314. * Shadow Render Object Function.
  32315. *
  32316. * @function shadowRenderObjectFunction
  32317. * @param {Object3D} object - The 3D object to render.
  32318. * @param {Scene} scene - The scene containing the object.
  32319. * @param {Camera} _camera - The camera used for rendering.
  32320. * @param {BufferGeometry} geometry - The geometry of the object.
  32321. * @param {Material} material - The material of the object.
  32322. * @param {Group} group - The group the object belongs to.
  32323. * @param {...any} params - Additional parameters for rendering.
  32324. */
  32325. /**
  32326. * TSL function for creating an instance of `ShadowNode`.
  32327. *
  32328. * @tsl
  32329. * @function
  32330. * @param {Light} light - The shadow casting light.
  32331. * @param {?LightShadow} [shadow] - The light shadow.
  32332. * @return {ShadowNode} The created shadow node.
  32333. */
  32334. const shadow = ( light, shadow ) => new ShadowNode( light, shadow );
  32335. const _clearColor$1 = /*@__PURE__*/ new Color();
  32336. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  32337. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  32338. const _lookTarget = /*@__PURE__*/ new Vector3();
  32339. // Cube map face directions and up vectors for point light shadows
  32340. // Face order: +X, -X, +Y, -Y, +Z, -Z
  32341. // WebGPU coordinate system - Y faces swapped to match texture sampling convention
  32342. const _cubeDirectionsWebGPU = [
  32343. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ),
  32344. /*@__PURE__*/ new Vector3( 0, 1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  32345. ];
  32346. const _cubeUpsWebGPU = [
  32347. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, -1 ),
  32348. /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  32349. ];
  32350. // WebGL coordinate system - standard OpenGL convention
  32351. const _cubeDirectionsWebGL = [
  32352. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, 1, 0 ),
  32353. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  32354. ];
  32355. const _cubeUpsWebGL = [
  32356. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ),
  32357. /*@__PURE__*/ new Vector3( 0, 0, -1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  32358. ];
  32359. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp } ) => {
  32360. return cubeTexture( depthTexture, bd3D ).compare( dp );
  32361. } );
  32362. /**
  32363. * A shadow filtering function for point lights using Vogel disk sampling and IGN.
  32364. *
  32365. * Uses 5 samples distributed via Vogel disk pattern in tangent space around the
  32366. * sample direction, rotated per-pixel using Interleaved Gradient Noise (IGN).
  32367. *
  32368. * @method
  32369. * @param {Object} inputs - The input parameter object.
  32370. * @param {CubeDepthTexture} inputs.depthTexture - A reference to the shadow cube map.
  32371. * @param {Node<vec3>} inputs.bd3D - The normalized direction from light to fragment.
  32372. * @param {Node<float>} inputs.dp - The depth value to compare against.
  32373. * @param {LightShadow} inputs.shadow - The light shadow.
  32374. * @return {Node<float>} The filtering result.
  32375. */
  32376. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, shadow } ) => {
  32377. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  32378. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  32379. const texelSize = radius.div( mapSize.x );
  32380. // Build a tangent-space coordinate system for applying offsets
  32381. const absDir = abs( bd3D );
  32382. const tangent = normalize( cross( bd3D, absDir.x.greaterThan( absDir.z ).select( vec3( 0, 1, 0 ), vec3( 1, 0, 0 ) ) ) );
  32383. const bitangent = cross( bd3D, tangent );
  32384. // Use IGN to rotate sampling pattern per pixel (phi = IGN * 2π)
  32385. const phi = interleavedGradientNoise( screenCoordinate.xy ).mul( 6.28318530718 );
  32386. // 5 samples using Vogel disk distribution in tangent space
  32387. const sample0 = vogelDiskSample( 0, 5, phi );
  32388. const sample1 = vogelDiskSample( 1, 5, phi );
  32389. const sample2 = vogelDiskSample( 2, 5, phi );
  32390. const sample3 = vogelDiskSample( 3, 5, phi );
  32391. const sample4 = vogelDiskSample( 4, 5, phi );
  32392. return cubeTexture( depthTexture, bd3D.add( tangent.mul( sample0.x ).add( bitangent.mul( sample0.y ) ).mul( texelSize ) ) ).compare( dp )
  32393. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample1.x ).add( bitangent.mul( sample1.y ) ).mul( texelSize ) ) ).compare( dp ) )
  32394. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample2.x ).add( bitangent.mul( sample2.y ) ).mul( texelSize ) ) ).compare( dp ) )
  32395. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample3.x ).add( bitangent.mul( sample3.y ) ).mul( texelSize ) ) ).compare( dp ) )
  32396. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample4.x ).add( bitangent.mul( sample4.y ) ).mul( texelSize ) ) ).compare( dp ) )
  32397. .mul( 1.0 / 5.0 );
  32398. } );
  32399. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow }, builder ) => {
  32400. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  32401. // the vector from the light to the world-space position of the fragment.
  32402. const shadowPosition = shadowCoord.xyz.toConst();
  32403. const shadowPositionAbs = shadowPosition.abs().toConst();
  32404. const viewZ = shadowPositionAbs.x.max( shadowPositionAbs.y ).max( shadowPositionAbs.z );
  32405. const shadowCameraNear = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  32406. const shadowCameraFar = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  32407. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  32408. const result = float( 1.0 ).toVar();
  32409. If( viewZ.sub( shadowCameraFar ).lessThanEqual( 0.0 ).and( viewZ.sub( shadowCameraNear ).greaterThanEqual( 0.0 ) ), () => {
  32410. let dp;
  32411. if ( builder.renderer.reversedDepthBuffer ) {
  32412. dp = viewZToReversedPerspectiveDepth( viewZ.negate(), shadowCameraNear, shadowCameraFar );
  32413. dp.subAssign( bias );
  32414. } else if ( builder.renderer.logarithmicDepthBuffer ) {
  32415. dp = viewZToLogarithmicDepth( viewZ.negate(), shadowCameraNear, shadowCameraFar );
  32416. dp.addAssign( bias );
  32417. } else {
  32418. dp = viewZToPerspectiveDepth( viewZ.negate(), shadowCameraNear, shadowCameraFar );
  32419. dp.addAssign( bias );
  32420. }
  32421. // bd3D = base direction 3D (direction from light to fragment)
  32422. const bd3D = shadowPosition.normalize();
  32423. // percentage-closer filtering using cube texture sampling
  32424. result.assign( filterFn( { depthTexture, bd3D, dp, shadow } ) );
  32425. } );
  32426. return result;
  32427. } );
  32428. /**
  32429. * Represents the shadow implementation for point light nodes.
  32430. *
  32431. * @augments ShadowNode
  32432. */
  32433. class PointShadowNode extends ShadowNode {
  32434. static get type() {
  32435. return 'PointShadowNode';
  32436. }
  32437. /**
  32438. * Constructs a new point shadow node.
  32439. *
  32440. * @param {PointLight} light - The shadow casting point light.
  32441. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  32442. */
  32443. constructor( light, shadow = null ) {
  32444. super( light, shadow );
  32445. }
  32446. /**
  32447. * Overwrites the default implementation to return point light shadow specific
  32448. * filtering functions.
  32449. *
  32450. * @param {number} type - The shadow type.
  32451. * @return {Function} The filtering function.
  32452. */
  32453. getShadowFilterFn( type ) {
  32454. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  32455. }
  32456. /**
  32457. * Overwrites the default implementation so the unaltered shadow position is used.
  32458. *
  32459. * @param {NodeBuilder} builder - A reference to the current node builder.
  32460. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  32461. * @return {Node<vec3>} The shadow coordinates.
  32462. */
  32463. setupShadowCoord( builder, shadowPosition ) {
  32464. return shadowPosition;
  32465. }
  32466. /**
  32467. * Overwrites the default implementation to only use point light specific
  32468. * shadow filter functions.
  32469. *
  32470. * @param {NodeBuilder} builder - A reference to the current node builder.
  32471. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  32472. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  32473. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's depth texture.
  32474. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  32475. * @param {LightShadow} inputs.shadow - The light shadow.
  32476. * @return {Node<float>} The result node of the shadow filtering.
  32477. */
  32478. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  32479. return pointShadowFilter( { filterFn, depthTexture, shadowCoord, shadow } );
  32480. }
  32481. /**
  32482. * Overwrites the default implementation to create a CubeRenderTarget with CubeDepthTexture.
  32483. *
  32484. * @param {LightShadow} shadow - The light shadow object.
  32485. * @param {NodeBuilder} builder - A reference to the current node builder.
  32486. * @return {Object} An object containing the shadow map and depth texture.
  32487. */
  32488. setupRenderTarget( shadow, builder ) {
  32489. const depthTexture = new CubeDepthTexture( shadow.mapSize.width );
  32490. depthTexture.name = 'PointShadowDepthTexture';
  32491. depthTexture.compareFunction = builder.renderer.reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare;
  32492. const shadowMap = builder.createCubeRenderTarget( shadow.mapSize.width );
  32493. shadowMap.texture.name = 'PointShadowMap';
  32494. shadowMap.depthTexture = depthTexture;
  32495. return { shadowMap, depthTexture };
  32496. }
  32497. /**
  32498. * Overwrites the default implementation with point light specific
  32499. * rendering code.
  32500. *
  32501. * @param {NodeFrame} frame - A reference to the current node frame.
  32502. */
  32503. renderShadow( frame ) {
  32504. const { shadow, shadowMap, light } = this;
  32505. const { renderer, scene } = frame;
  32506. const camera = shadow.camera;
  32507. const shadowMatrix = shadow.matrix;
  32508. // Select cube directions/ups based on coordinate system
  32509. const isWebGPU = renderer.coordinateSystem === WebGPUCoordinateSystem;
  32510. const cubeDirections = isWebGPU ? _cubeDirectionsWebGPU : _cubeDirectionsWebGL;
  32511. const cubeUps = isWebGPU ? _cubeUpsWebGPU : _cubeUpsWebGL;
  32512. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.width );
  32513. //
  32514. const previousAutoClear = renderer.autoClear;
  32515. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  32516. const previousClearAlpha = renderer.getClearAlpha();
  32517. renderer.autoClear = false;
  32518. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  32519. // Render each cube face
  32520. for ( let face = 0; face < 6; face ++ ) {
  32521. // Set render target to the specific cube face
  32522. renderer.setRenderTarget( shadowMap, face );
  32523. renderer.clear();
  32524. // Update shadow camera matrices for this face
  32525. const far = light.distance || camera.far;
  32526. if ( far !== camera.far ) {
  32527. camera.far = far;
  32528. camera.updateProjectionMatrix();
  32529. }
  32530. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  32531. camera.position.copy( _lightPositionWorld );
  32532. _lookTarget.copy( camera.position );
  32533. _lookTarget.add( cubeDirections[ face ] );
  32534. camera.up.copy( cubeUps[ face ] );
  32535. camera.lookAt( _lookTarget );
  32536. camera.updateMatrixWorld();
  32537. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  32538. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  32539. shadow._frustum.setFromProjectionMatrix( _projScreenMatrix$1, camera.coordinateSystem, camera.reversedDepth );
  32540. //
  32541. const currentSceneName = scene.name;
  32542. scene.name = `Point Light Shadow [ ${ light.name || 'ID: ' + light.id } ] - Face ${ face + 1 }`;
  32543. renderer.render( scene, camera );
  32544. scene.name = currentSceneName;
  32545. }
  32546. //
  32547. renderer.autoClear = previousAutoClear;
  32548. renderer.setClearColor( previousClearColor, previousClearAlpha );
  32549. }
  32550. }
  32551. /**
  32552. * TSL function for creating an instance of `PointShadowNode`.
  32553. *
  32554. * @tsl
  32555. * @function
  32556. * @param {PointLight} light - The shadow casting point light.
  32557. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  32558. * @return {PointShadowNode} The created point shadow node.
  32559. */
  32560. const pointShadow = ( light, shadow ) => new PointShadowNode( light, shadow );
  32561. /**
  32562. * Base class for analytic light nodes.
  32563. *
  32564. * @augments LightingNode
  32565. */
  32566. class AnalyticLightNode extends LightingNode {
  32567. static get type() {
  32568. return 'AnalyticLightNode';
  32569. }
  32570. /**
  32571. * Constructs a new analytic light node.
  32572. *
  32573. * @param {?Light} [light=null] - The light source.
  32574. */
  32575. constructor( light = null ) {
  32576. super();
  32577. /**
  32578. * The light source.
  32579. *
  32580. * @type {?Light}
  32581. * @default null
  32582. */
  32583. this.light = light;
  32584. /**
  32585. * The light's color value.
  32586. *
  32587. * @type {Color}
  32588. */
  32589. this.color = new Color();
  32590. /**
  32591. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  32592. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  32593. *
  32594. * @type {Node}
  32595. */
  32596. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  32597. /**
  32598. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  32599. * The final color node is represented by a different node when using shadows.
  32600. *
  32601. * @type {?Node}
  32602. * @default null
  32603. */
  32604. this.baseColorNode = null;
  32605. /**
  32606. * Represents the light's shadow.
  32607. *
  32608. * @type {?ShadowNode}
  32609. * @default null
  32610. */
  32611. this.shadowNode = null;
  32612. /**
  32613. * Represents the light's shadow color.
  32614. *
  32615. * @type {?Node}
  32616. * @default null
  32617. */
  32618. this.shadowColorNode = null;
  32619. /**
  32620. * This flag can be used for type testing.
  32621. *
  32622. * @type {boolean}
  32623. * @readonly
  32624. * @default true
  32625. */
  32626. this.isAnalyticLightNode = true;
  32627. /**
  32628. * Overwritten since analytic light nodes are updated
  32629. * once per frame.
  32630. *
  32631. * @type {string}
  32632. * @default 'frame'
  32633. */
  32634. this.updateType = NodeUpdateType.FRAME;
  32635. if ( light && light.shadow ) {
  32636. this._shadowDisposeListener = () => {
  32637. this.disposeShadow();
  32638. };
  32639. light.addEventListener( 'dispose', this._shadowDisposeListener );
  32640. }
  32641. }
  32642. dispose() {
  32643. if ( this._shadowDisposeListener ) {
  32644. this.light.removeEventListener( 'dispose', this._shadowDisposeListener );
  32645. }
  32646. super.dispose();
  32647. }
  32648. /**
  32649. * Frees internal resources related to shadows.
  32650. */
  32651. disposeShadow() {
  32652. if ( this.shadowNode !== null ) {
  32653. this.shadowNode.dispose();
  32654. this.shadowNode = null;
  32655. }
  32656. this.shadowColorNode = null;
  32657. if ( this.baseColorNode !== null ) {
  32658. this.colorNode = this.baseColorNode;
  32659. this.baseColorNode = null;
  32660. }
  32661. }
  32662. getHash() {
  32663. return this.light.uuid;
  32664. }
  32665. /**
  32666. * Returns a node representing a direction vector which points from the current
  32667. * position in view space to the light's position in view space.
  32668. *
  32669. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  32670. * @return {Node<vec3>} The light vector node.
  32671. */
  32672. getLightVector( builder ) {
  32673. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  32674. }
  32675. /**
  32676. * Sets up the direct lighting for the analytic light node.
  32677. *
  32678. * @abstract
  32679. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  32680. * @return {Object|undefined} The direct light data (color and direction).
  32681. */
  32682. setupDirect( /*builder*/ ) { }
  32683. /**
  32684. * Sets up the direct rect area lighting for the analytic light node.
  32685. *
  32686. * @abstract
  32687. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  32688. * @return {Object|undefined} The direct rect area light data.
  32689. */
  32690. setupDirectRectArea( /*builder*/ ) { }
  32691. /**
  32692. * Setups the shadow node for this light. The method exists so concrete light classes
  32693. * can setup different types of shadow nodes.
  32694. *
  32695. * @return {ShadowNode} The created shadow node.
  32696. */
  32697. setupShadowNode() {
  32698. return shadow( this.light );
  32699. }
  32700. /**
  32701. * Setups the shadow for this light. This method is only executed if the light
  32702. * cast shadows and the current build object receives shadows. It incorporates
  32703. * shadows into the lighting computation.
  32704. *
  32705. * @param {NodeBuilder} builder - The current node builder.
  32706. */
  32707. setupShadow( builder ) {
  32708. const { renderer } = builder;
  32709. if ( renderer.shadowMap.enabled === false ) return;
  32710. let shadowColorNode = this.shadowColorNode;
  32711. if ( shadowColorNode === null ) {
  32712. const customShadowNode = this.light.shadow.shadowNode;
  32713. let shadowNode;
  32714. if ( customShadowNode !== undefined ) {
  32715. shadowNode = nodeObject( customShadowNode );
  32716. } else {
  32717. shadowNode = this.setupShadowNode();
  32718. }
  32719. this.shadowNode = shadowNode;
  32720. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  32721. this.baseColorNode = this.colorNode;
  32722. }
  32723. //
  32724. if ( builder.context.getShadow ) {
  32725. shadowColorNode = builder.context.getShadow( this, builder );
  32726. }
  32727. this.colorNode = shadowColorNode;
  32728. }
  32729. /**
  32730. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  32731. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  32732. * invocate the respective interface methods.
  32733. *
  32734. * @param {NodeBuilder} builder - The current node builder.
  32735. */
  32736. setup( builder ) {
  32737. this.colorNode = this.baseColorNode || this.colorNode;
  32738. if ( this.light.castShadow ) {
  32739. if ( builder.object.receiveShadow ) {
  32740. this.setupShadow( builder );
  32741. }
  32742. } else if ( this.shadowNode !== null ) {
  32743. this.shadowNode.dispose();
  32744. this.shadowNode = null;
  32745. this.shadowColorNode = null;
  32746. }
  32747. const directLightData = this.setupDirect( builder );
  32748. const directRectAreaLightData = this.setupDirectRectArea( builder );
  32749. if ( directLightData ) {
  32750. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  32751. }
  32752. if ( directRectAreaLightData ) {
  32753. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  32754. }
  32755. }
  32756. /**
  32757. * The update method is used to update light uniforms per frame.
  32758. * Potentially overwritten in concrete light nodes to update light
  32759. * specific uniforms.
  32760. *
  32761. * @param {NodeFrame} frame - A reference to the current node frame.
  32762. */
  32763. update( /*frame*/ ) {
  32764. const { light } = this;
  32765. this.color.copy( light.color ).multiplyScalar( light.intensity );
  32766. }
  32767. }
  32768. /**
  32769. * Represents a `discard` shader operation in TSL.
  32770. *
  32771. * @method
  32772. * @param {Object} inputs - The input parameter object.
  32773. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  32774. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  32775. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  32776. * @return {Node<float>} The distance falloff.
  32777. */
  32778. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  32779. // based upon Frostbite 3 Moving to Physically-based Rendering
  32780. // page 32, equation 26: E[window1]
  32781. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  32782. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  32783. return cutoffDistance.greaterThan( 0 ).select(
  32784. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  32785. distanceFalloff
  32786. );
  32787. } ); // validated
  32788. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  32789. const lightDirection = lightVector.normalize();
  32790. const lightDistance = lightVector.length();
  32791. const attenuation = getDistanceAttenuation( {
  32792. lightDistance,
  32793. cutoffDistance,
  32794. decayExponent
  32795. } );
  32796. const lightColor = color.mul( attenuation );
  32797. return { lightDirection, lightColor };
  32798. };
  32799. /**
  32800. * Module for representing point lights as nodes.
  32801. *
  32802. * @augments AnalyticLightNode
  32803. */
  32804. class PointLightNode extends AnalyticLightNode {
  32805. static get type() {
  32806. return 'PointLightNode';
  32807. }
  32808. /**
  32809. * Constructs a new point light node.
  32810. *
  32811. * @param {?PointLight} [light=null] - The point light source.
  32812. */
  32813. constructor( light = null ) {
  32814. super( light );
  32815. /**
  32816. * Uniform node representing the cutoff distance.
  32817. *
  32818. * @type {UniformNode<float>}
  32819. */
  32820. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  32821. /**
  32822. * Uniform node representing the decay exponent.
  32823. *
  32824. * @type {UniformNode<float>}
  32825. */
  32826. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  32827. }
  32828. /**
  32829. * Overwritten to updated point light specific uniforms.
  32830. *
  32831. * @param {NodeFrame} frame - A reference to the current node frame.
  32832. */
  32833. update( frame ) {
  32834. const { light } = this;
  32835. super.update( frame );
  32836. this.cutoffDistanceNode.value = light.distance;
  32837. this.decayExponentNode.value = light.decay;
  32838. }
  32839. /**
  32840. * Overwritten to setup point light specific shadow.
  32841. *
  32842. * @return {PointShadowNode}
  32843. */
  32844. setupShadowNode() {
  32845. return pointShadow( this.light );
  32846. }
  32847. setupDirect( builder ) {
  32848. return directPointLight( {
  32849. color: this.colorNode,
  32850. lightVector: this.getLightVector( builder ),
  32851. cutoffDistance: this.cutoffDistanceNode,
  32852. decayExponent: this.decayExponentNode
  32853. } );
  32854. }
  32855. }
  32856. /**
  32857. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  32858. *
  32859. * @tsl
  32860. * @function
  32861. * @param {Node<vec2>} coord - The uv coordinates.
  32862. * @return {Node<float>} The result data.
  32863. */
  32864. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  32865. const uv = coord.mul( 2.0 );
  32866. const cx = uv.x.floor();
  32867. const cy = uv.y.floor();
  32868. const result = cx.add( cy ).mod( 2.0 );
  32869. return result.sign();
  32870. } );
  32871. /**
  32872. * Generates a circle based on the uv coordinates.
  32873. *
  32874. * @tsl
  32875. * @function
  32876. * @param {Node<vec2>} coord - The uv to generate the circle.
  32877. * @return {Node<float>} The circle shape.
  32878. */
  32879. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  32880. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  32881. let alpha;
  32882. if ( material.alphaToCoverage && renderer.currentSamples > 0 ) {
  32883. const dlen = float( len2.fwidth() ).toVar();
  32884. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  32885. } else {
  32886. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  32887. }
  32888. return alpha;
  32889. } );
  32890. // Three.js Transpiler
  32891. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  32892. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  32893. const f = float( f_immutable ).toVar();
  32894. const t = float( t_immutable ).toVar();
  32895. const b = bool( b_immutable ).toVar();
  32896. return select( b, t, f ).uniformFlow();
  32897. } ).setLayout( {
  32898. name: 'mx_select',
  32899. type: 'float',
  32900. inputs: [
  32901. { name: 'b', type: 'bool' },
  32902. { name: 't', type: 'float' },
  32903. { name: 'f', type: 'float' }
  32904. ]
  32905. } );
  32906. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  32907. const b = bool( b_immutable ).toVar();
  32908. const val = float( val_immutable ).toVar();
  32909. return select( b, val.negate(), val ).uniformFlow();
  32910. } ).setLayout( {
  32911. name: 'mx_negate_if',
  32912. type: 'float',
  32913. inputs: [
  32914. { name: 'val', type: 'float' },
  32915. { name: 'b', type: 'bool' }
  32916. ]
  32917. } );
  32918. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32919. const x = float( x_immutable ).toVar();
  32920. return int( floor( x ) );
  32921. } ).setLayout( {
  32922. name: 'mx_floor',
  32923. type: 'int',
  32924. inputs: [
  32925. { name: 'x', type: 'float' }
  32926. ]
  32927. } );
  32928. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  32929. const x = float( x_immutable ).toVar();
  32930. i.assign( mx_floor( x ) );
  32931. return x.sub( float( i ) );
  32932. } );
  32933. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  32934. const t = float( t_immutable ).toVar();
  32935. const s = float( s_immutable ).toVar();
  32936. const v3 = float( v3_immutable ).toVar();
  32937. const v2 = float( v2_immutable ).toVar();
  32938. const v1 = float( v1_immutable ).toVar();
  32939. const v0 = float( v0_immutable ).toVar();
  32940. const s1 = float( sub( 1.0, s ) ).toVar();
  32941. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  32942. } ).setLayout( {
  32943. name: 'mx_bilerp_0',
  32944. type: 'float',
  32945. inputs: [
  32946. { name: 'v0', type: 'float' },
  32947. { name: 'v1', type: 'float' },
  32948. { name: 'v2', type: 'float' },
  32949. { name: 'v3', type: 'float' },
  32950. { name: 's', type: 'float' },
  32951. { name: 't', type: 'float' }
  32952. ]
  32953. } );
  32954. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  32955. const t = float( t_immutable ).toVar();
  32956. const s = float( s_immutable ).toVar();
  32957. const v3 = vec3( v3_immutable ).toVar();
  32958. const v2 = vec3( v2_immutable ).toVar();
  32959. const v1 = vec3( v1_immutable ).toVar();
  32960. const v0 = vec3( v0_immutable ).toVar();
  32961. const s1 = float( sub( 1.0, s ) ).toVar();
  32962. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  32963. } ).setLayout( {
  32964. name: 'mx_bilerp_1',
  32965. type: 'vec3',
  32966. inputs: [
  32967. { name: 'v0', type: 'vec3' },
  32968. { name: 'v1', type: 'vec3' },
  32969. { name: 'v2', type: 'vec3' },
  32970. { name: 'v3', type: 'vec3' },
  32971. { name: 's', type: 'float' },
  32972. { name: 't', type: 'float' }
  32973. ]
  32974. } );
  32975. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  32976. 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 ] ) => {
  32977. const r = float( r_immutable ).toVar();
  32978. const t = float( t_immutable ).toVar();
  32979. const s = float( s_immutable ).toVar();
  32980. const v7 = float( v7_immutable ).toVar();
  32981. const v6 = float( v6_immutable ).toVar();
  32982. const v5 = float( v5_immutable ).toVar();
  32983. const v4 = float( v4_immutable ).toVar();
  32984. const v3 = float( v3_immutable ).toVar();
  32985. const v2 = float( v2_immutable ).toVar();
  32986. const v1 = float( v1_immutable ).toVar();
  32987. const v0 = float( v0_immutable ).toVar();
  32988. const s1 = float( sub( 1.0, s ) ).toVar();
  32989. const t1 = float( sub( 1.0, t ) ).toVar();
  32990. const r1 = float( sub( 1.0, r ) ).toVar();
  32991. 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 ) ) ) ) ) );
  32992. } ).setLayout( {
  32993. name: 'mx_trilerp_0',
  32994. type: 'float',
  32995. inputs: [
  32996. { name: 'v0', type: 'float' },
  32997. { name: 'v1', type: 'float' },
  32998. { name: 'v2', type: 'float' },
  32999. { name: 'v3', type: 'float' },
  33000. { name: 'v4', type: 'float' },
  33001. { name: 'v5', type: 'float' },
  33002. { name: 'v6', type: 'float' },
  33003. { name: 'v7', type: 'float' },
  33004. { name: 's', type: 'float' },
  33005. { name: 't', type: 'float' },
  33006. { name: 'r', type: 'float' }
  33007. ]
  33008. } );
  33009. 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 ] ) => {
  33010. const r = float( r_immutable ).toVar();
  33011. const t = float( t_immutable ).toVar();
  33012. const s = float( s_immutable ).toVar();
  33013. const v7 = vec3( v7_immutable ).toVar();
  33014. const v6 = vec3( v6_immutable ).toVar();
  33015. const v5 = vec3( v5_immutable ).toVar();
  33016. const v4 = vec3( v4_immutable ).toVar();
  33017. const v3 = vec3( v3_immutable ).toVar();
  33018. const v2 = vec3( v2_immutable ).toVar();
  33019. const v1 = vec3( v1_immutable ).toVar();
  33020. const v0 = vec3( v0_immutable ).toVar();
  33021. const s1 = float( sub( 1.0, s ) ).toVar();
  33022. const t1 = float( sub( 1.0, t ) ).toVar();
  33023. const r1 = float( sub( 1.0, r ) ).toVar();
  33024. 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 ) ) ) ) ) );
  33025. } ).setLayout( {
  33026. name: 'mx_trilerp_1',
  33027. type: 'vec3',
  33028. inputs: [
  33029. { name: 'v0', type: 'vec3' },
  33030. { name: 'v1', type: 'vec3' },
  33031. { name: 'v2', type: 'vec3' },
  33032. { name: 'v3', type: 'vec3' },
  33033. { name: 'v4', type: 'vec3' },
  33034. { name: 'v5', type: 'vec3' },
  33035. { name: 'v6', type: 'vec3' },
  33036. { name: 'v7', type: 'vec3' },
  33037. { name: 's', type: 'float' },
  33038. { name: 't', type: 'float' },
  33039. { name: 'r', type: 'float' }
  33040. ]
  33041. } );
  33042. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  33043. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  33044. const y = float( y_immutable ).toVar();
  33045. const x = float( x_immutable ).toVar();
  33046. const hash = uint( hash_immutable ).toVar();
  33047. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  33048. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  33049. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  33050. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  33051. } ).setLayout( {
  33052. name: 'mx_gradient_float_0',
  33053. type: 'float',
  33054. inputs: [
  33055. { name: 'hash', type: 'uint' },
  33056. { name: 'x', type: 'float' },
  33057. { name: 'y', type: 'float' }
  33058. ]
  33059. } );
  33060. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  33061. const z = float( z_immutable ).toVar();
  33062. const y = float( y_immutable ).toVar();
  33063. const x = float( x_immutable ).toVar();
  33064. const hash = uint( hash_immutable ).toVar();
  33065. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  33066. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  33067. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  33068. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  33069. } ).setLayout( {
  33070. name: 'mx_gradient_float_1',
  33071. type: 'float',
  33072. inputs: [
  33073. { name: 'hash', type: 'uint' },
  33074. { name: 'x', type: 'float' },
  33075. { name: 'y', type: 'float' },
  33076. { name: 'z', type: 'float' }
  33077. ]
  33078. } );
  33079. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  33080. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  33081. const y = float( y_immutable ).toVar();
  33082. const x = float( x_immutable ).toVar();
  33083. const hash = uvec3( hash_immutable ).toVar();
  33084. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  33085. } ).setLayout( {
  33086. name: 'mx_gradient_vec3_0',
  33087. type: 'vec3',
  33088. inputs: [
  33089. { name: 'hash', type: 'uvec3' },
  33090. { name: 'x', type: 'float' },
  33091. { name: 'y', type: 'float' }
  33092. ]
  33093. } );
  33094. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  33095. const z = float( z_immutable ).toVar();
  33096. const y = float( y_immutable ).toVar();
  33097. const x = float( x_immutable ).toVar();
  33098. const hash = uvec3( hash_immutable ).toVar();
  33099. 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 ) );
  33100. } ).setLayout( {
  33101. name: 'mx_gradient_vec3_1',
  33102. type: 'vec3',
  33103. inputs: [
  33104. { name: 'hash', type: 'uvec3' },
  33105. { name: 'x', type: 'float' },
  33106. { name: 'y', type: 'float' },
  33107. { name: 'z', type: 'float' }
  33108. ]
  33109. } );
  33110. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  33111. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  33112. const v = float( v_immutable ).toVar();
  33113. return mul( 0.6616, v );
  33114. } ).setLayout( {
  33115. name: 'mx_gradient_scale2d_0',
  33116. type: 'float',
  33117. inputs: [
  33118. { name: 'v', type: 'float' }
  33119. ]
  33120. } );
  33121. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  33122. const v = float( v_immutable ).toVar();
  33123. return mul( 0.9820, v );
  33124. } ).setLayout( {
  33125. name: 'mx_gradient_scale3d_0',
  33126. type: 'float',
  33127. inputs: [
  33128. { name: 'v', type: 'float' }
  33129. ]
  33130. } );
  33131. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  33132. const v = vec3( v_immutable ).toVar();
  33133. return mul( 0.6616, v );
  33134. } ).setLayout( {
  33135. name: 'mx_gradient_scale2d_1',
  33136. type: 'vec3',
  33137. inputs: [
  33138. { name: 'v', type: 'vec3' }
  33139. ]
  33140. } );
  33141. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  33142. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  33143. const v = vec3( v_immutable ).toVar();
  33144. return mul( 0.9820, v );
  33145. } ).setLayout( {
  33146. name: 'mx_gradient_scale3d_1',
  33147. type: 'vec3',
  33148. inputs: [
  33149. { name: 'v', type: 'vec3' }
  33150. ]
  33151. } );
  33152. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  33153. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  33154. const k = int( k_immutable ).toVar();
  33155. const x = uint( x_immutable ).toVar();
  33156. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  33157. } ).setLayout( {
  33158. name: 'mx_rotl32',
  33159. type: 'uint',
  33160. inputs: [
  33161. { name: 'x', type: 'uint' },
  33162. { name: 'k', type: 'int' }
  33163. ]
  33164. } );
  33165. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  33166. a.subAssign( c );
  33167. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  33168. c.addAssign( b );
  33169. b.subAssign( a );
  33170. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  33171. a.addAssign( c );
  33172. c.subAssign( b );
  33173. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  33174. b.addAssign( a );
  33175. a.subAssign( c );
  33176. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  33177. c.addAssign( b );
  33178. b.subAssign( a );
  33179. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  33180. a.addAssign( c );
  33181. c.subAssign( b );
  33182. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  33183. b.addAssign( a );
  33184. } );
  33185. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  33186. const c = uint( c_immutable ).toVar();
  33187. const b = uint( b_immutable ).toVar();
  33188. const a = uint( a_immutable ).toVar();
  33189. c.bitXorAssign( b );
  33190. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  33191. a.bitXorAssign( c );
  33192. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  33193. b.bitXorAssign( a );
  33194. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  33195. c.bitXorAssign( b );
  33196. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  33197. a.bitXorAssign( c );
  33198. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  33199. b.bitXorAssign( a );
  33200. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  33201. c.bitXorAssign( b );
  33202. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  33203. return c;
  33204. } ).setLayout( {
  33205. name: 'mx_bjfinal',
  33206. type: 'uint',
  33207. inputs: [
  33208. { name: 'a', type: 'uint' },
  33209. { name: 'b', type: 'uint' },
  33210. { name: 'c', type: 'uint' }
  33211. ]
  33212. } );
  33213. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  33214. const bits = uint( bits_immutable ).toVar();
  33215. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  33216. } ).setLayout( {
  33217. name: 'mx_bits_to_01',
  33218. type: 'float',
  33219. inputs: [
  33220. { name: 'bits', type: 'uint' }
  33221. ]
  33222. } );
  33223. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  33224. const t = float( t_immutable ).toVar();
  33225. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  33226. } ).setLayout( {
  33227. name: 'mx_fade',
  33228. type: 'float',
  33229. inputs: [
  33230. { name: 't', type: 'float' }
  33231. ]
  33232. } );
  33233. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  33234. const x = int( x_immutable ).toVar();
  33235. const len = uint( uint( 1 ) ).toVar();
  33236. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  33237. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  33238. } ).setLayout( {
  33239. name: 'mx_hash_int_0',
  33240. type: 'uint',
  33241. inputs: [
  33242. { name: 'x', type: 'int' }
  33243. ]
  33244. } );
  33245. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  33246. const y = int( y_immutable ).toVar();
  33247. const x = int( x_immutable ).toVar();
  33248. const len = uint( uint( 2 ) ).toVar();
  33249. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  33250. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  33251. a.addAssign( uint( x ) );
  33252. b.addAssign( uint( y ) );
  33253. return mx_bjfinal( a, b, c );
  33254. } ).setLayout( {
  33255. name: 'mx_hash_int_1',
  33256. type: 'uint',
  33257. inputs: [
  33258. { name: 'x', type: 'int' },
  33259. { name: 'y', type: 'int' }
  33260. ]
  33261. } );
  33262. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  33263. const z = int( z_immutable ).toVar();
  33264. const y = int( y_immutable ).toVar();
  33265. const x = int( x_immutable ).toVar();
  33266. const len = uint( uint( 3 ) ).toVar();
  33267. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  33268. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  33269. a.addAssign( uint( x ) );
  33270. b.addAssign( uint( y ) );
  33271. c.addAssign( uint( z ) );
  33272. return mx_bjfinal( a, b, c );
  33273. } ).setLayout( {
  33274. name: 'mx_hash_int_2',
  33275. type: 'uint',
  33276. inputs: [
  33277. { name: 'x', type: 'int' },
  33278. { name: 'y', type: 'int' },
  33279. { name: 'z', type: 'int' }
  33280. ]
  33281. } );
  33282. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  33283. const xx = int( xx_immutable ).toVar();
  33284. const z = int( z_immutable ).toVar();
  33285. const y = int( y_immutable ).toVar();
  33286. const x = int( x_immutable ).toVar();
  33287. const len = uint( uint( 4 ) ).toVar();
  33288. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  33289. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  33290. a.addAssign( uint( x ) );
  33291. b.addAssign( uint( y ) );
  33292. c.addAssign( uint( z ) );
  33293. mx_bjmix( a, b, c );
  33294. a.addAssign( uint( xx ) );
  33295. return mx_bjfinal( a, b, c );
  33296. } ).setLayout( {
  33297. name: 'mx_hash_int_3',
  33298. type: 'uint',
  33299. inputs: [
  33300. { name: 'x', type: 'int' },
  33301. { name: 'y', type: 'int' },
  33302. { name: 'z', type: 'int' },
  33303. { name: 'xx', type: 'int' }
  33304. ]
  33305. } );
  33306. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  33307. const yy = int( yy_immutable ).toVar();
  33308. const xx = int( xx_immutable ).toVar();
  33309. const z = int( z_immutable ).toVar();
  33310. const y = int( y_immutable ).toVar();
  33311. const x = int( x_immutable ).toVar();
  33312. const len = uint( uint( 5 ) ).toVar();
  33313. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  33314. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  33315. a.addAssign( uint( x ) );
  33316. b.addAssign( uint( y ) );
  33317. c.addAssign( uint( z ) );
  33318. mx_bjmix( a, b, c );
  33319. a.addAssign( uint( xx ) );
  33320. b.addAssign( uint( yy ) );
  33321. return mx_bjfinal( a, b, c );
  33322. } ).setLayout( {
  33323. name: 'mx_hash_int_4',
  33324. type: 'uint',
  33325. inputs: [
  33326. { name: 'x', type: 'int' },
  33327. { name: 'y', type: 'int' },
  33328. { name: 'z', type: 'int' },
  33329. { name: 'xx', type: 'int' },
  33330. { name: 'yy', type: 'int' }
  33331. ]
  33332. } );
  33333. 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 ] );
  33334. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  33335. const y = int( y_immutable ).toVar();
  33336. const x = int( x_immutable ).toVar();
  33337. const h = uint( mx_hash_int( x, y ) ).toVar();
  33338. const result = uvec3().toVar();
  33339. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  33340. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  33341. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  33342. return result;
  33343. } ).setLayout( {
  33344. name: 'mx_hash_vec3_0',
  33345. type: 'uvec3',
  33346. inputs: [
  33347. { name: 'x', type: 'int' },
  33348. { name: 'y', type: 'int' }
  33349. ]
  33350. } );
  33351. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  33352. const z = int( z_immutable ).toVar();
  33353. const y = int( y_immutable ).toVar();
  33354. const x = int( x_immutable ).toVar();
  33355. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  33356. const result = uvec3().toVar();
  33357. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  33358. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  33359. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  33360. return result;
  33361. } ).setLayout( {
  33362. name: 'mx_hash_vec3_1',
  33363. type: 'uvec3',
  33364. inputs: [
  33365. { name: 'x', type: 'int' },
  33366. { name: 'y', type: 'int' },
  33367. { name: 'z', type: 'int' }
  33368. ]
  33369. } );
  33370. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  33371. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33372. const p = vec2( p_immutable ).toVar();
  33373. const X = int().toVar(), Y = int().toVar();
  33374. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  33375. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  33376. const u = float( mx_fade( fx ) ).toVar();
  33377. const v = float( mx_fade( fy ) ).toVar();
  33378. 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();
  33379. return mx_gradient_scale2d( result );
  33380. } ).setLayout( {
  33381. name: 'mx_perlin_noise_float_0',
  33382. type: 'float',
  33383. inputs: [
  33384. { name: 'p', type: 'vec2' }
  33385. ]
  33386. } );
  33387. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33388. const p = vec3( p_immutable ).toVar();
  33389. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33390. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  33391. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  33392. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  33393. const u = float( mx_fade( fx ) ).toVar();
  33394. const v = float( mx_fade( fy ) ).toVar();
  33395. const w = float( mx_fade( fz ) ).toVar();
  33396. 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();
  33397. return mx_gradient_scale3d( result );
  33398. } ).setLayout( {
  33399. name: 'mx_perlin_noise_float_1',
  33400. type: 'float',
  33401. inputs: [
  33402. { name: 'p', type: 'vec3' }
  33403. ]
  33404. } );
  33405. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  33406. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33407. const p = vec2( p_immutable ).toVar();
  33408. const X = int().toVar(), Y = int().toVar();
  33409. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  33410. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  33411. const u = float( mx_fade( fx ) ).toVar();
  33412. const v = float( mx_fade( fy ) ).toVar();
  33413. 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();
  33414. return mx_gradient_scale2d( result );
  33415. } ).setLayout( {
  33416. name: 'mx_perlin_noise_vec3_0',
  33417. type: 'vec3',
  33418. inputs: [
  33419. { name: 'p', type: 'vec2' }
  33420. ]
  33421. } );
  33422. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33423. const p = vec3( p_immutable ).toVar();
  33424. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33425. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  33426. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  33427. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  33428. const u = float( mx_fade( fx ) ).toVar();
  33429. const v = float( mx_fade( fy ) ).toVar();
  33430. const w = float( mx_fade( fz ) ).toVar();
  33431. 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();
  33432. return mx_gradient_scale3d( result );
  33433. } ).setLayout( {
  33434. name: 'mx_perlin_noise_vec3_1',
  33435. type: 'vec3',
  33436. inputs: [
  33437. { name: 'p', type: 'vec3' }
  33438. ]
  33439. } );
  33440. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  33441. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33442. const p = float( p_immutable ).toVar();
  33443. const ix = int( mx_floor( p ) ).toVar();
  33444. return mx_bits_to_01( mx_hash_int( ix ) );
  33445. } ).setLayout( {
  33446. name: 'mx_cell_noise_float_0',
  33447. type: 'float',
  33448. inputs: [
  33449. { name: 'p', type: 'float' }
  33450. ]
  33451. } );
  33452. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33453. const p = vec2( p_immutable ).toVar();
  33454. const ix = int( mx_floor( p.x ) ).toVar();
  33455. const iy = int( mx_floor( p.y ) ).toVar();
  33456. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  33457. } ).setLayout( {
  33458. name: 'mx_cell_noise_float_1',
  33459. type: 'float',
  33460. inputs: [
  33461. { name: 'p', type: 'vec2' }
  33462. ]
  33463. } );
  33464. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33465. const p = vec3( p_immutable ).toVar();
  33466. const ix = int( mx_floor( p.x ) ).toVar();
  33467. const iy = int( mx_floor( p.y ) ).toVar();
  33468. const iz = int( mx_floor( p.z ) ).toVar();
  33469. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  33470. } ).setLayout( {
  33471. name: 'mx_cell_noise_float_2',
  33472. type: 'float',
  33473. inputs: [
  33474. { name: 'p', type: 'vec3' }
  33475. ]
  33476. } );
  33477. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33478. const p = vec4( p_immutable ).toVar();
  33479. const ix = int( mx_floor( p.x ) ).toVar();
  33480. const iy = int( mx_floor( p.y ) ).toVar();
  33481. const iz = int( mx_floor( p.z ) ).toVar();
  33482. const iw = int( mx_floor( p.w ) ).toVar();
  33483. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  33484. } ).setLayout( {
  33485. name: 'mx_cell_noise_float_3',
  33486. type: 'float',
  33487. inputs: [
  33488. { name: 'p', type: 'vec4' }
  33489. ]
  33490. } );
  33491. 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 ] );
  33492. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33493. const p = float( p_immutable ).toVar();
  33494. const ix = int( mx_floor( p ) ).toVar();
  33495. 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 ) ) ) );
  33496. } ).setLayout( {
  33497. name: 'mx_cell_noise_vec3_0',
  33498. type: 'vec3',
  33499. inputs: [
  33500. { name: 'p', type: 'float' }
  33501. ]
  33502. } );
  33503. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33504. const p = vec2( p_immutable ).toVar();
  33505. const ix = int( mx_floor( p.x ) ).toVar();
  33506. const iy = int( mx_floor( p.y ) ).toVar();
  33507. 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 ) ) ) );
  33508. } ).setLayout( {
  33509. name: 'mx_cell_noise_vec3_1',
  33510. type: 'vec3',
  33511. inputs: [
  33512. { name: 'p', type: 'vec2' }
  33513. ]
  33514. } );
  33515. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33516. const p = vec3( p_immutable ).toVar();
  33517. const ix = int( mx_floor( p.x ) ).toVar();
  33518. const iy = int( mx_floor( p.y ) ).toVar();
  33519. const iz = int( mx_floor( p.z ) ).toVar();
  33520. 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 ) ) ) );
  33521. } ).setLayout( {
  33522. name: 'mx_cell_noise_vec3_2',
  33523. type: 'vec3',
  33524. inputs: [
  33525. { name: 'p', type: 'vec3' }
  33526. ]
  33527. } );
  33528. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  33529. const p = vec4( p_immutable ).toVar();
  33530. const ix = int( mx_floor( p.x ) ).toVar();
  33531. const iy = int( mx_floor( p.y ) ).toVar();
  33532. const iz = int( mx_floor( p.z ) ).toVar();
  33533. const iw = int( mx_floor( p.w ) ).toVar();
  33534. 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 ) ) ) );
  33535. } ).setLayout( {
  33536. name: 'mx_cell_noise_vec3_3',
  33537. type: 'vec3',
  33538. inputs: [
  33539. { name: 'p', type: 'vec4' }
  33540. ]
  33541. } );
  33542. 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 ] );
  33543. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  33544. const diminish = float( diminish_immutable ).toVar();
  33545. const lacunarity = float( lacunarity_immutable ).toVar();
  33546. const octaves = int( octaves_immutable ).toVar();
  33547. const p = vec3( p_immutable ).toVar();
  33548. const result = float( 0.0 ).toVar();
  33549. const amplitude = float( 1.0 ).toVar();
  33550. Loop( octaves, () => {
  33551. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  33552. amplitude.mulAssign( diminish );
  33553. p.mulAssign( lacunarity );
  33554. } );
  33555. return result;
  33556. } ).setLayout( {
  33557. name: 'mx_fractal_noise_float',
  33558. type: 'float',
  33559. inputs: [
  33560. { name: 'p', type: 'vec3' },
  33561. { name: 'octaves', type: 'int' },
  33562. { name: 'lacunarity', type: 'float' },
  33563. { name: 'diminish', type: 'float' }
  33564. ]
  33565. } );
  33566. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  33567. const diminish = float( diminish_immutable ).toVar();
  33568. const lacunarity = float( lacunarity_immutable ).toVar();
  33569. const octaves = int( octaves_immutable ).toVar();
  33570. const p = vec3( p_immutable ).toVar();
  33571. const result = vec3( 0.0 ).toVar();
  33572. const amplitude = float( 1.0 ).toVar();
  33573. Loop( octaves, () => {
  33574. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  33575. amplitude.mulAssign( diminish );
  33576. p.mulAssign( lacunarity );
  33577. } );
  33578. return result;
  33579. } ).setLayout( {
  33580. name: 'mx_fractal_noise_vec3',
  33581. type: 'vec3',
  33582. inputs: [
  33583. { name: 'p', type: 'vec3' },
  33584. { name: 'octaves', type: 'int' },
  33585. { name: 'lacunarity', type: 'float' },
  33586. { name: 'diminish', type: 'float' }
  33587. ]
  33588. } );
  33589. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  33590. const diminish = float( diminish_immutable ).toVar();
  33591. const lacunarity = float( lacunarity_immutable ).toVar();
  33592. const octaves = int( octaves_immutable ).toVar();
  33593. const p = vec3( p_immutable ).toVar();
  33594. 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 ) );
  33595. } ).setLayout( {
  33596. name: 'mx_fractal_noise_vec2',
  33597. type: 'vec2',
  33598. inputs: [
  33599. { name: 'p', type: 'vec3' },
  33600. { name: 'octaves', type: 'int' },
  33601. { name: 'lacunarity', type: 'float' },
  33602. { name: 'diminish', type: 'float' }
  33603. ]
  33604. } );
  33605. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  33606. const diminish = float( diminish_immutable ).toVar();
  33607. const lacunarity = float( lacunarity_immutable ).toVar();
  33608. const octaves = int( octaves_immutable ).toVar();
  33609. const p = vec3( p_immutable ).toVar();
  33610. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  33611. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  33612. return vec4( c, f );
  33613. } ).setLayout( {
  33614. name: 'mx_fractal_noise_vec4',
  33615. type: 'vec4',
  33616. inputs: [
  33617. { name: 'p', type: 'vec3' },
  33618. { name: 'octaves', type: 'int' },
  33619. { name: 'lacunarity', type: 'float' },
  33620. { name: 'diminish', type: 'float' }
  33621. ]
  33622. } );
  33623. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  33624. const metric = int( metric_immutable ).toVar();
  33625. const jitter = float( jitter_immutable ).toVar();
  33626. const yoff = int( yoff_immutable ).toVar();
  33627. const xoff = int( xoff_immutable ).toVar();
  33628. const y = int( y_immutable ).toVar();
  33629. const x = int( x_immutable ).toVar();
  33630. const p = vec2( p_immutable ).toVar();
  33631. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  33632. const off = vec2( tmp.x, tmp.y ).toVar();
  33633. off.subAssign( 0.5 );
  33634. off.mulAssign( jitter );
  33635. off.addAssign( 0.5 );
  33636. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  33637. const diff = vec2( cellpos.sub( p ) ).toVar();
  33638. If( metric.equal( int( 2 ) ), () => {
  33639. return abs( diff.x ).add( abs( diff.y ) );
  33640. } );
  33641. If( metric.equal( int( 3 ) ), () => {
  33642. return max$1( abs( diff.x ), abs( diff.y ) );
  33643. } );
  33644. return dot( diff, diff );
  33645. } ).setLayout( {
  33646. name: 'mx_worley_distance_0',
  33647. type: 'float',
  33648. inputs: [
  33649. { name: 'p', type: 'vec2' },
  33650. { name: 'x', type: 'int' },
  33651. { name: 'y', type: 'int' },
  33652. { name: 'xoff', type: 'int' },
  33653. { name: 'yoff', type: 'int' },
  33654. { name: 'jitter', type: 'float' },
  33655. { name: 'metric', type: 'int' }
  33656. ]
  33657. } );
  33658. 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 ] ) => {
  33659. const metric = int( metric_immutable ).toVar();
  33660. const jitter = float( jitter_immutable ).toVar();
  33661. const zoff = int( zoff_immutable ).toVar();
  33662. const yoff = int( yoff_immutable ).toVar();
  33663. const xoff = int( xoff_immutable ).toVar();
  33664. const z = int( z_immutable ).toVar();
  33665. const y = int( y_immutable ).toVar();
  33666. const x = int( x_immutable ).toVar();
  33667. const p = vec3( p_immutable ).toVar();
  33668. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  33669. off.subAssign( 0.5 );
  33670. off.mulAssign( jitter );
  33671. off.addAssign( 0.5 );
  33672. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  33673. const diff = vec3( cellpos.sub( p ) ).toVar();
  33674. If( metric.equal( int( 2 ) ), () => {
  33675. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  33676. } );
  33677. If( metric.equal( int( 3 ) ), () => {
  33678. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  33679. } );
  33680. return dot( diff, diff );
  33681. } ).setLayout( {
  33682. name: 'mx_worley_distance_1',
  33683. type: 'float',
  33684. inputs: [
  33685. { name: 'p', type: 'vec3' },
  33686. { name: 'x', type: 'int' },
  33687. { name: 'y', type: 'int' },
  33688. { name: 'z', type: 'int' },
  33689. { name: 'xoff', type: 'int' },
  33690. { name: 'yoff', type: 'int' },
  33691. { name: 'zoff', type: 'int' },
  33692. { name: 'jitter', type: 'float' },
  33693. { name: 'metric', type: 'int' }
  33694. ]
  33695. } );
  33696. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  33697. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33698. const metric = int( metric_immutable ).toVar();
  33699. const jitter = float( jitter_immutable ).toVar();
  33700. const p = vec2( p_immutable ).toVar();
  33701. const X = int().toVar(), Y = int().toVar();
  33702. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33703. const sqdist = float( 1e6 ).toVar();
  33704. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33705. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33706. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33707. sqdist.assign( min$1( sqdist, dist ) );
  33708. } );
  33709. } );
  33710. If( metric.equal( int( 0 ) ), () => {
  33711. sqdist.assign( sqrt( sqdist ) );
  33712. } );
  33713. return sqdist;
  33714. } ).setLayout( {
  33715. name: 'mx_worley_noise_float_0',
  33716. type: 'float',
  33717. inputs: [
  33718. { name: 'p', type: 'vec2' },
  33719. { name: 'jitter', type: 'float' },
  33720. { name: 'metric', type: 'int' }
  33721. ]
  33722. } );
  33723. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33724. const metric = int( metric_immutable ).toVar();
  33725. const jitter = float( jitter_immutable ).toVar();
  33726. const p = vec2( p_immutable ).toVar();
  33727. const X = int().toVar(), Y = int().toVar();
  33728. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33729. const sqdist = vec2( 1e6, 1e6 ).toVar();
  33730. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33731. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33732. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33733. If( dist.lessThan( sqdist.x ), () => {
  33734. sqdist.y.assign( sqdist.x );
  33735. sqdist.x.assign( dist );
  33736. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33737. sqdist.y.assign( dist );
  33738. } );
  33739. } );
  33740. } );
  33741. If( metric.equal( int( 0 ) ), () => {
  33742. sqdist.assign( sqrt( sqdist ) );
  33743. } );
  33744. return sqdist;
  33745. } ).setLayout( {
  33746. name: 'mx_worley_noise_vec2_0',
  33747. type: 'vec2',
  33748. inputs: [
  33749. { name: 'p', type: 'vec2' },
  33750. { name: 'jitter', type: 'float' },
  33751. { name: 'metric', type: 'int' }
  33752. ]
  33753. } );
  33754. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33755. const metric = int( metric_immutable ).toVar();
  33756. const jitter = float( jitter_immutable ).toVar();
  33757. const p = vec2( p_immutable ).toVar();
  33758. const X = int().toVar(), Y = int().toVar();
  33759. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33760. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  33761. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33762. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33763. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33764. If( dist.lessThan( sqdist.x ), () => {
  33765. sqdist.z.assign( sqdist.y );
  33766. sqdist.y.assign( sqdist.x );
  33767. sqdist.x.assign( dist );
  33768. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33769. sqdist.z.assign( sqdist.y );
  33770. sqdist.y.assign( dist );
  33771. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  33772. sqdist.z.assign( dist );
  33773. } );
  33774. } );
  33775. } );
  33776. If( metric.equal( int( 0 ) ), () => {
  33777. sqdist.assign( sqrt( sqdist ) );
  33778. } );
  33779. return sqdist;
  33780. } ).setLayout( {
  33781. name: 'mx_worley_noise_vec3_0',
  33782. type: 'vec3',
  33783. inputs: [
  33784. { name: 'p', type: 'vec2' },
  33785. { name: 'jitter', type: 'float' },
  33786. { name: 'metric', type: 'int' }
  33787. ]
  33788. } );
  33789. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33790. const metric = int( metric_immutable ).toVar();
  33791. const jitter = float( jitter_immutable ).toVar();
  33792. const p = vec3( p_immutable ).toVar();
  33793. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33794. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33795. const sqdist = float( 1e6 ).toVar();
  33796. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33797. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33798. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33799. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33800. sqdist.assign( min$1( sqdist, dist ) );
  33801. } );
  33802. } );
  33803. } );
  33804. If( metric.equal( int( 0 ) ), () => {
  33805. sqdist.assign( sqrt( sqdist ) );
  33806. } );
  33807. return sqdist;
  33808. } ).setLayout( {
  33809. name: 'mx_worley_noise_float_1',
  33810. type: 'float',
  33811. inputs: [
  33812. { name: 'p', type: 'vec3' },
  33813. { name: 'jitter', type: 'float' },
  33814. { name: 'metric', type: 'int' }
  33815. ]
  33816. } );
  33817. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  33818. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33819. const metric = int( metric_immutable ).toVar();
  33820. const jitter = float( jitter_immutable ).toVar();
  33821. const p = vec3( p_immutable ).toVar();
  33822. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33823. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33824. const sqdist = vec2( 1e6, 1e6 ).toVar();
  33825. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33826. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33827. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33828. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33829. If( dist.lessThan( sqdist.x ), () => {
  33830. sqdist.y.assign( sqdist.x );
  33831. sqdist.x.assign( dist );
  33832. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33833. sqdist.y.assign( dist );
  33834. } );
  33835. } );
  33836. } );
  33837. } );
  33838. If( metric.equal( int( 0 ) ), () => {
  33839. sqdist.assign( sqrt( sqdist ) );
  33840. } );
  33841. return sqdist;
  33842. } ).setLayout( {
  33843. name: 'mx_worley_noise_vec2_1',
  33844. type: 'vec2',
  33845. inputs: [
  33846. { name: 'p', type: 'vec3' },
  33847. { name: 'jitter', type: 'float' },
  33848. { name: 'metric', type: 'int' }
  33849. ]
  33850. } );
  33851. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  33852. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33853. const metric = int( metric_immutable ).toVar();
  33854. const jitter = float( jitter_immutable ).toVar();
  33855. const p = vec3( p_immutable ).toVar();
  33856. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33857. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33858. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  33859. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33860. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33861. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33862. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33863. If( dist.lessThan( sqdist.x ), () => {
  33864. sqdist.z.assign( sqdist.y );
  33865. sqdist.y.assign( sqdist.x );
  33866. sqdist.x.assign( dist );
  33867. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33868. sqdist.z.assign( sqdist.y );
  33869. sqdist.y.assign( dist );
  33870. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  33871. sqdist.z.assign( dist );
  33872. } );
  33873. } );
  33874. } );
  33875. } );
  33876. If( metric.equal( int( 0 ) ), () => {
  33877. sqdist.assign( sqrt( sqdist ) );
  33878. } );
  33879. return sqdist;
  33880. } ).setLayout( {
  33881. name: 'mx_worley_noise_vec3_1',
  33882. type: 'vec3',
  33883. inputs: [
  33884. { name: 'p', type: 'vec3' },
  33885. { name: 'jitter', type: 'float' },
  33886. { name: 'metric', type: 'int' }
  33887. ]
  33888. } );
  33889. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  33890. // Unified Noise 2D
  33891. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  33892. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  33893. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  33894. octaves_immutable, lacunarity_immutable, diminish_immutable
  33895. ] ) => {
  33896. const noiseType = int( noiseType_immutable ).toVar();
  33897. const texcoord = vec2( texcoord_immutable ).toVar();
  33898. const freq = vec2( freq_immutable ).toVar();
  33899. const offset = vec2( offset_immutable ).toVar();
  33900. const jitter = float( jitter_immutable ).toVar();
  33901. const outmin = float( outmin_immutable ).toVar();
  33902. const outmax = float( outmax_immutable ).toVar();
  33903. const clampoutput = bool( clampoutput_immutable ).toVar();
  33904. const octaves = int( octaves_immutable ).toVar();
  33905. const lacunarity = float( lacunarity_immutable ).toVar();
  33906. const diminish = float( diminish_immutable ).toVar();
  33907. // Compute input position
  33908. const p = texcoord.mul( freq ).add( offset );
  33909. const result = float( 0.0 ).toVar();
  33910. // Perlin
  33911. If( noiseType.equal( int( 0 ) ), () => {
  33912. result.assign( mx_perlin_noise_vec3( p ) );
  33913. } );
  33914. // Cell
  33915. If( noiseType.equal( int( 1 ) ), () => {
  33916. result.assign( mx_cell_noise_vec3( p ) );
  33917. } );
  33918. // Worley (metric=0 = euclidean)
  33919. If( noiseType.equal( int( 2 ) ), () => {
  33920. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  33921. } );
  33922. // Fractal (use vec3(p, 0.0) for 2D input)
  33923. If( noiseType.equal( int( 3 ) ), () => {
  33924. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  33925. } );
  33926. // Remap output to [outmin, outmax]
  33927. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  33928. // Clamp if requested
  33929. If( clampoutput, () => {
  33930. result.assign( clamp( result, outmin, outmax ) );
  33931. } );
  33932. return result;
  33933. } ).setLayout( {
  33934. name: 'mx_unifiednoise2d',
  33935. type: 'float',
  33936. inputs: [
  33937. { name: 'noiseType', type: 'int' },
  33938. { name: 'texcoord', type: 'vec2' },
  33939. { name: 'freq', type: 'vec2' },
  33940. { name: 'offset', type: 'vec2' },
  33941. { name: 'jitter', type: 'float' },
  33942. { name: 'outmin', type: 'float' },
  33943. { name: 'outmax', type: 'float' },
  33944. { name: 'clampoutput', type: 'bool' },
  33945. { name: 'octaves', type: 'int' },
  33946. { name: 'lacunarity', type: 'float' },
  33947. { name: 'diminish', type: 'float' }
  33948. ]
  33949. } );
  33950. // Unified Noise 3D
  33951. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  33952. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  33953. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  33954. octaves_immutable, lacunarity_immutable, diminish_immutable
  33955. ] ) => {
  33956. const noiseType = int( noiseType_immutable ).toVar();
  33957. const position = vec3( position_immutable ).toVar();
  33958. const freq = vec3( freq_immutable ).toVar();
  33959. const offset = vec3( offset_immutable ).toVar();
  33960. const jitter = float( jitter_immutable ).toVar();
  33961. const outmin = float( outmin_immutable ).toVar();
  33962. const outmax = float( outmax_immutable ).toVar();
  33963. const clampoutput = bool( clampoutput_immutable ).toVar();
  33964. const octaves = int( octaves_immutable ).toVar();
  33965. const lacunarity = float( lacunarity_immutable ).toVar();
  33966. const diminish = float( diminish_immutable ).toVar();
  33967. // Compute input position
  33968. const p = position.mul( freq ).add( offset );
  33969. const result = float( 0.0 ).toVar();
  33970. // Perlin
  33971. If( noiseType.equal( int( 0 ) ), () => {
  33972. result.assign( mx_perlin_noise_vec3( p ) );
  33973. } );
  33974. // Cell
  33975. If( noiseType.equal( int( 1 ) ), () => {
  33976. result.assign( mx_cell_noise_vec3( p ) );
  33977. } );
  33978. // Worley (metric=0 = euclidean)
  33979. If( noiseType.equal( int( 2 ) ), () => {
  33980. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  33981. } );
  33982. // Fractal
  33983. If( noiseType.equal( int( 3 ) ), () => {
  33984. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  33985. } );
  33986. // Remap output to [outmin, outmax]
  33987. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  33988. // Clamp if requested
  33989. If( clampoutput, () => {
  33990. result.assign( clamp( result, outmin, outmax ) );
  33991. } );
  33992. return result;
  33993. } ).setLayout( {
  33994. name: 'mx_unifiednoise3d',
  33995. type: 'float',
  33996. inputs: [
  33997. { name: 'noiseType', type: 'int' },
  33998. { name: 'position', type: 'vec3' },
  33999. { name: 'freq', type: 'vec3' },
  34000. { name: 'offset', type: 'vec3' },
  34001. { name: 'jitter', type: 'float' },
  34002. { name: 'outmin', type: 'float' },
  34003. { name: 'outmax', type: 'float' },
  34004. { name: 'clampoutput', type: 'bool' },
  34005. { name: 'octaves', type: 'int' },
  34006. { name: 'lacunarity', type: 'float' },
  34007. { name: 'diminish', type: 'float' }
  34008. ]
  34009. } );
  34010. // Three.js Transpiler
  34011. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  34012. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  34013. const s = hsv.y;
  34014. const v = hsv.z;
  34015. const result = vec3().toVar();
  34016. If( s.lessThan( 0.0001 ), () => {
  34017. result.assign( vec3( v, v, v ) );
  34018. } ).Else( () => {
  34019. let h = hsv.x;
  34020. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  34021. const hi = int( trunc( h ) );
  34022. const f = h.sub( float( hi ) );
  34023. const p = v.mul( s.oneMinus() );
  34024. const q = v.mul( s.mul( f ).oneMinus() );
  34025. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  34026. If( hi.equal( int( 0 ) ), () => {
  34027. result.assign( vec3( v, t, p ) );
  34028. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  34029. result.assign( vec3( q, v, p ) );
  34030. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  34031. result.assign( vec3( p, v, t ) );
  34032. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  34033. result.assign( vec3( p, q, v ) );
  34034. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  34035. result.assign( vec3( t, p, v ) );
  34036. } ).Else( () => {
  34037. result.assign( vec3( v, p, q ) );
  34038. } );
  34039. } );
  34040. return result;
  34041. } ).setLayout( {
  34042. name: 'mx_hsvtorgb',
  34043. type: 'vec3',
  34044. inputs: [
  34045. { name: 'hsv', type: 'vec3' }
  34046. ]
  34047. } );
  34048. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  34049. const c = vec3( c_immutable ).toVar();
  34050. const r = float( c.x ).toVar();
  34051. const g = float( c.y ).toVar();
  34052. const b = float( c.z ).toVar();
  34053. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  34054. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  34055. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  34056. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  34057. v.assign( maxcomp );
  34058. If( maxcomp.greaterThan( 0.0 ), () => {
  34059. s.assign( delta.div( maxcomp ) );
  34060. } ).Else( () => {
  34061. s.assign( 0.0 );
  34062. } );
  34063. If( s.lessThanEqual( 0.0 ), () => {
  34064. h.assign( 0.0 );
  34065. } ).Else( () => {
  34066. If( r.greaterThanEqual( maxcomp ), () => {
  34067. h.assign( g.sub( b ).div( delta ) );
  34068. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  34069. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  34070. } ).Else( () => {
  34071. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  34072. } );
  34073. h.mulAssign( 1.0 / 6.0 );
  34074. If( h.lessThan( 0.0 ), () => {
  34075. h.addAssign( 1.0 );
  34076. } );
  34077. } );
  34078. return vec3( h, s, v );
  34079. } ).setLayout( {
  34080. name: 'mx_rgbtohsv',
  34081. type: 'vec3',
  34082. inputs: [
  34083. { name: 'c', type: 'vec3' }
  34084. ]
  34085. } );
  34086. // Three.js Transpiler
  34087. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  34088. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  34089. const color = vec3( color_immutable ).toVar();
  34090. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  34091. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  34092. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  34093. return mix( linSeg, powSeg, isAbove );
  34094. } ).setLayout( {
  34095. name: 'mx_srgb_texture_to_lin_rec709',
  34096. type: 'vec3',
  34097. inputs: [
  34098. { name: 'color', type: 'vec3' }
  34099. ]
  34100. } );
  34101. const mx_aastep = ( threshold, value ) => {
  34102. threshold = float( threshold );
  34103. value = float( value );
  34104. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  34105. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  34106. };
  34107. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  34108. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  34109. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  34110. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  34111. const mx_ramp4 = (
  34112. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  34113. ) => {
  34114. const u = texcoord.x.clamp();
  34115. const v = texcoord.y.clamp();
  34116. const top = mix( valuetl, valuetr, u );
  34117. const bottom = mix( valuebl, valuebr, u );
  34118. return mix( top, bottom, v );
  34119. };
  34120. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  34121. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  34122. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  34123. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  34124. const mx_safepower = ( in1, in2 = 1 ) => {
  34125. in1 = float( in1 );
  34126. return in1.abs().pow( in2 ).mul( in1.sign() );
  34127. };
  34128. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  34129. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34130. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34131. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34132. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  34133. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  34134. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  34135. return noise_vec4.mul( amplitude ).add( pivot );
  34136. };
  34137. 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 );
  34138. 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 );
  34139. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34140. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34141. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34142. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  34143. 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 );
  34144. 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 );
  34145. 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 );
  34146. 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 );
  34147. // === Moved from MaterialXLoader.js ===
  34148. // Math ops
  34149. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  34150. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  34151. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  34152. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  34153. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  34154. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  34155. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  34156. const mx_timer = () => time;
  34157. const mx_frame = () => frameId;
  34158. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  34159. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  34160. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  34161. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  34162. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  34163. const mx_separate = ( in1, channelOrOut = null ) => {
  34164. if ( typeof channelOrOut === 'string' ) {
  34165. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  34166. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  34167. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  34168. }
  34169. if ( typeof channelOrOut === 'number' ) {
  34170. return in1.element( channelOrOut );
  34171. }
  34172. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  34173. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  34174. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  34175. }
  34176. return in1;
  34177. };
  34178. const mx_place2d = (
  34179. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  34180. ) => {
  34181. let uv = texcoord;
  34182. if ( pivot ) uv = uv.sub( pivot );
  34183. if ( scale ) uv = uv.mul( scale );
  34184. if ( rotate ) {
  34185. const rad = rotate.mul( Math.PI / 180.0 );
  34186. const cosR = rad.cos();
  34187. const sinR = rad.sin();
  34188. uv = vec2(
  34189. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  34190. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  34191. );
  34192. }
  34193. if ( pivot ) uv = uv.add( pivot );
  34194. if ( offset ) uv = uv.add( offset );
  34195. return uv;
  34196. };
  34197. const mx_rotate2d = ( input, amount ) => {
  34198. input = vec2( input );
  34199. amount = float( amount );
  34200. const radians = amount.mul( Math.PI / 180.0 );
  34201. return rotate( input, radians );
  34202. };
  34203. const mx_rotate3d = ( input, amount, axis ) => {
  34204. input = vec3( input );
  34205. amount = float( amount );
  34206. axis = vec3( axis );
  34207. const radians = amount.mul( Math.PI / 180.0 );
  34208. const nAxis = axis.normalize();
  34209. const cosA = radians.cos();
  34210. const sinA = radians.sin();
  34211. const oneMinusCosA = float( 1 ).sub( cosA );
  34212. const rot =
  34213. input.mul( cosA )
  34214. .add( nAxis.cross( input ).mul( sinA ) )
  34215. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  34216. return rot;
  34217. };
  34218. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  34219. input = vec3( input );
  34220. scale = float( scale );
  34221. return bumpMap( input, scale );
  34222. };
  34223. /**
  34224. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  34225. *
  34226. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  34227. *
  34228. * ```js
  34229. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  34230. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  34231. * ```
  34232. *
  34233. * @tsl
  34234. * @function
  34235. * @param {Node<vec3>} normal - The normal to correct.
  34236. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  34237. * @param {Node<vec3>} cubePos - The cube position.
  34238. * @return {Node<vec3>} The parallax corrected normal.
  34239. */
  34240. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  34241. const nDir = normalize( normal ).toVar();
  34242. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  34243. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  34244. const rbminmax = vec3().toVar();
  34245. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  34246. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  34247. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  34248. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  34249. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  34250. return boxIntersection.sub( cubePos );
  34251. } );
  34252. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  34253. // normal is assumed to have unit length
  34254. const x = normal.x, y = normal.y, z = normal.z;
  34255. // band 0
  34256. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  34257. // band 1
  34258. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  34259. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  34260. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  34261. // band 2
  34262. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  34263. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  34264. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  34265. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  34266. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  34267. return result;
  34268. } );
  34269. // constants
  34270. var TSL = /*#__PURE__*/Object.freeze({
  34271. __proto__: null,
  34272. BRDF_GGX: BRDF_GGX,
  34273. BRDF_Lambert: BRDF_Lambert,
  34274. BasicPointShadowFilter: BasicPointShadowFilter,
  34275. BasicShadowFilter: BasicShadowFilter,
  34276. Break: Break,
  34277. Const: Const,
  34278. Continue: Continue,
  34279. DFGLUT: DFGLUT,
  34280. D_GGX: D_GGX,
  34281. Discard: Discard,
  34282. EPSILON: EPSILON,
  34283. F_Schlick: F_Schlick,
  34284. Fn: Fn,
  34285. HALF_PI: HALF_PI,
  34286. INFINITY: INFINITY,
  34287. If: If,
  34288. Loop: Loop,
  34289. NodeAccess: NodeAccess,
  34290. NodeShaderStage: NodeShaderStage,
  34291. NodeType: NodeType,
  34292. NodeUpdateType: NodeUpdateType,
  34293. OnBeforeFrameUpdate: OnBeforeFrameUpdate,
  34294. OnBeforeMaterialUpdate: OnBeforeMaterialUpdate,
  34295. OnBeforeObjectUpdate: OnBeforeObjectUpdate,
  34296. OnFrameUpdate: OnFrameUpdate,
  34297. OnMaterialUpdate: OnMaterialUpdate,
  34298. OnObjectUpdate: OnObjectUpdate,
  34299. PCFShadowFilter: PCFShadowFilter,
  34300. PCFSoftShadowFilter: PCFSoftShadowFilter,
  34301. PI: PI,
  34302. PI2: PI2,
  34303. PointShadowFilter: PointShadowFilter,
  34304. Return: Return,
  34305. Schlick_to_F0: Schlick_to_F0,
  34306. ShaderNode: ShaderNode,
  34307. Stack: Stack,
  34308. Switch: Switch,
  34309. TBNViewMatrix: TBNViewMatrix,
  34310. TWO_PI: TWO_PI,
  34311. VSMShadowFilter: VSMShadowFilter,
  34312. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  34313. Var: Var,
  34314. VarIntent: VarIntent,
  34315. abs: abs,
  34316. acesFilmicToneMapping: acesFilmicToneMapping,
  34317. acos: acos,
  34318. acosh: acosh,
  34319. add: add,
  34320. addMethodChaining: addMethodChaining,
  34321. addNodeElement: addNodeElement,
  34322. agxToneMapping: agxToneMapping,
  34323. all: all,
  34324. alphaT: alphaT,
  34325. ambientOcclusion: ambientOcclusion,
  34326. and: and,
  34327. anisotropy: anisotropy,
  34328. anisotropyB: anisotropyB,
  34329. anisotropyT: anisotropyT,
  34330. any: any,
  34331. append: append,
  34332. array: array,
  34333. asin: asin,
  34334. asinh: asinh,
  34335. assign: assign,
  34336. atan: atan,
  34337. atanh: atanh,
  34338. atomicAdd: atomicAdd,
  34339. atomicAnd: atomicAnd,
  34340. atomicFunc: atomicFunc,
  34341. atomicLoad: atomicLoad,
  34342. atomicMax: atomicMax,
  34343. atomicMin: atomicMin,
  34344. atomicOr: atomicOr,
  34345. atomicStore: atomicStore,
  34346. atomicSub: atomicSub,
  34347. atomicXor: atomicXor,
  34348. attenuationColor: attenuationColor,
  34349. attenuationDistance: attenuationDistance,
  34350. attribute: attribute,
  34351. attributeArray: attributeArray,
  34352. backgroundBlurriness: backgroundBlurriness,
  34353. backgroundIntensity: backgroundIntensity,
  34354. backgroundRotation: backgroundRotation,
  34355. batch: batch,
  34356. batchColor: batchColor,
  34357. bentNormalView: bentNormalView,
  34358. billboarding: billboarding,
  34359. bitAnd: bitAnd,
  34360. bitNot: bitNot,
  34361. bitOr: bitOr,
  34362. bitXor: bitXor,
  34363. bitangentGeometry: bitangentGeometry,
  34364. bitangentLocal: bitangentLocal,
  34365. bitangentView: bitangentView,
  34366. bitangentWorld: bitangentWorld,
  34367. bitcast: bitcast,
  34368. blendBurn: blendBurn,
  34369. blendColor: blendColor,
  34370. blendDodge: blendDodge,
  34371. blendOverlay: blendOverlay,
  34372. blendScreen: blendScreen,
  34373. blur: blur,
  34374. bool: bool,
  34375. buffer: buffer,
  34376. bufferAttribute: bufferAttribute,
  34377. builtin: builtin,
  34378. builtinAOContext: builtinAOContext,
  34379. builtinShadowContext: builtinShadowContext,
  34380. bumpMap: bumpMap,
  34381. bvec2: bvec2,
  34382. bvec3: bvec3,
  34383. bvec4: bvec4,
  34384. bypass: bypass,
  34385. cache: cache,
  34386. call: call,
  34387. cameraFar: cameraFar,
  34388. cameraIndex: cameraIndex,
  34389. cameraNear: cameraNear,
  34390. cameraNormalMatrix: cameraNormalMatrix,
  34391. cameraPosition: cameraPosition,
  34392. cameraProjectionMatrix: cameraProjectionMatrix,
  34393. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  34394. cameraViewMatrix: cameraViewMatrix,
  34395. cameraViewport: cameraViewport,
  34396. cameraWorldMatrix: cameraWorldMatrix,
  34397. cbrt: cbrt,
  34398. cdl: cdl,
  34399. ceil: ceil,
  34400. checker: checker,
  34401. cineonToneMapping: cineonToneMapping,
  34402. clamp: clamp,
  34403. clearcoat: clearcoat,
  34404. clearcoatNormalView: clearcoatNormalView,
  34405. clearcoatRoughness: clearcoatRoughness,
  34406. clipSpace: clipSpace,
  34407. code: code,
  34408. color: color,
  34409. colorSpaceToWorking: colorSpaceToWorking,
  34410. colorToDirection: colorToDirection,
  34411. compute: compute,
  34412. computeKernel: computeKernel,
  34413. computeSkinning: computeSkinning,
  34414. context: context,
  34415. convert: convert,
  34416. convertColorSpace: convertColorSpace,
  34417. convertToTexture: convertToTexture,
  34418. cos: cos,
  34419. cosh: cosh,
  34420. countLeadingZeros: countLeadingZeros,
  34421. countOneBits: countOneBits,
  34422. countTrailingZeros: countTrailingZeros,
  34423. cross: cross,
  34424. cubeTexture: cubeTexture,
  34425. cubeTextureBase: cubeTextureBase,
  34426. dFdx: dFdx,
  34427. dFdy: dFdy,
  34428. dashSize: dashSize,
  34429. debug: debug,
  34430. decrement: decrement,
  34431. decrementBefore: decrementBefore,
  34432. defaultBuildStages: defaultBuildStages,
  34433. defaultShaderStages: defaultShaderStages,
  34434. defined: defined,
  34435. degrees: degrees,
  34436. deltaTime: deltaTime,
  34437. densityFogFactor: densityFogFactor,
  34438. depth: depth,
  34439. depthPass: depthPass,
  34440. determinant: determinant,
  34441. difference: difference,
  34442. diffuseColor: diffuseColor,
  34443. diffuseContribution: diffuseContribution,
  34444. directPointLight: directPointLight,
  34445. directionToColor: directionToColor,
  34446. directionToFaceDirection: directionToFaceDirection,
  34447. dispersion: dispersion,
  34448. disposeShadowMaterial: disposeShadowMaterial,
  34449. distance: distance,
  34450. div: div,
  34451. dot: dot,
  34452. drawIndex: drawIndex,
  34453. dynamicBufferAttribute: dynamicBufferAttribute,
  34454. element: element,
  34455. emissive: emissive,
  34456. equal: equal,
  34457. equirectDirection: equirectDirection,
  34458. equirectUV: equirectUV,
  34459. exp: exp,
  34460. exp2: exp2,
  34461. exponentialHeightFogFactor: exponentialHeightFogFactor,
  34462. expression: expression,
  34463. faceDirection: faceDirection,
  34464. faceForward: faceForward,
  34465. faceforward: faceforward,
  34466. float: float,
  34467. floatBitsToInt: floatBitsToInt,
  34468. floatBitsToUint: floatBitsToUint,
  34469. floor: floor,
  34470. fog: fog,
  34471. fract: fract,
  34472. frameGroup: frameGroup,
  34473. frameId: frameId,
  34474. frontFacing: frontFacing,
  34475. fwidth: fwidth,
  34476. gain: gain,
  34477. gapSize: gapSize,
  34478. getConstNodeType: getConstNodeType,
  34479. getCurrentStack: getCurrentStack,
  34480. getDirection: getDirection,
  34481. getDistanceAttenuation: getDistanceAttenuation,
  34482. getGeometryRoughness: getGeometryRoughness,
  34483. getNormalFromDepth: getNormalFromDepth,
  34484. getParallaxCorrectNormal: getParallaxCorrectNormal,
  34485. getRoughness: getRoughness,
  34486. getScreenPosition: getScreenPosition,
  34487. getShIrradianceAt: getShIrradianceAt,
  34488. getShadowMaterial: getShadowMaterial,
  34489. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  34490. getTextureIndex: getTextureIndex,
  34491. getViewPosition: getViewPosition,
  34492. ggxConvolution: ggxConvolution,
  34493. globalId: globalId,
  34494. glsl: glsl,
  34495. glslFn: glslFn,
  34496. grayscale: grayscale,
  34497. greaterThan: greaterThan,
  34498. greaterThanEqual: greaterThanEqual,
  34499. hash: hash,
  34500. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  34501. highpModelViewMatrix: highpModelViewMatrix,
  34502. hue: hue,
  34503. increment: increment,
  34504. incrementBefore: incrementBefore,
  34505. inspector: inspector,
  34506. instance: instance,
  34507. instanceColor: instanceColor,
  34508. instanceIndex: instanceIndex,
  34509. instancedArray: instancedArray,
  34510. instancedBufferAttribute: instancedBufferAttribute,
  34511. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  34512. instancedMesh: instancedMesh,
  34513. int: int,
  34514. intBitsToFloat: intBitsToFloat,
  34515. interleavedGradientNoise: interleavedGradientNoise,
  34516. inverse: inverse,
  34517. inverseSqrt: inverseSqrt,
  34518. inversesqrt: inversesqrt,
  34519. invocationLocalIndex: invocationLocalIndex,
  34520. invocationSubgroupIndex: invocationSubgroupIndex,
  34521. ior: ior,
  34522. iridescence: iridescence,
  34523. iridescenceIOR: iridescenceIOR,
  34524. iridescenceThickness: iridescenceThickness,
  34525. isolate: isolate,
  34526. ivec2: ivec2,
  34527. ivec3: ivec3,
  34528. ivec4: ivec4,
  34529. js: js,
  34530. label: label,
  34531. length: length,
  34532. lengthSq: lengthSq,
  34533. lessThan: lessThan,
  34534. lessThanEqual: lessThanEqual,
  34535. lightPosition: lightPosition,
  34536. lightProjectionUV: lightProjectionUV,
  34537. lightShadowMatrix: lightShadowMatrix,
  34538. lightTargetDirection: lightTargetDirection,
  34539. lightTargetPosition: lightTargetPosition,
  34540. lightViewPosition: lightViewPosition,
  34541. lightingContext: lightingContext,
  34542. lights: lights,
  34543. linearDepth: linearDepth,
  34544. linearToneMapping: linearToneMapping,
  34545. localId: localId,
  34546. log: log,
  34547. log2: log2,
  34548. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  34549. luminance: luminance,
  34550. mat2: mat2,
  34551. mat3: mat3,
  34552. mat4: mat4,
  34553. matcapUV: matcapUV,
  34554. materialAO: materialAO,
  34555. materialAlphaTest: materialAlphaTest,
  34556. materialAnisotropy: materialAnisotropy,
  34557. materialAnisotropyVector: materialAnisotropyVector,
  34558. materialAttenuationColor: materialAttenuationColor,
  34559. materialAttenuationDistance: materialAttenuationDistance,
  34560. materialClearcoat: materialClearcoat,
  34561. materialClearcoatNormal: materialClearcoatNormal,
  34562. materialClearcoatRoughness: materialClearcoatRoughness,
  34563. materialColor: materialColor,
  34564. materialDispersion: materialDispersion,
  34565. materialEmissive: materialEmissive,
  34566. materialEnvIntensity: materialEnvIntensity,
  34567. materialEnvRotation: materialEnvRotation,
  34568. materialIOR: materialIOR,
  34569. materialIridescence: materialIridescence,
  34570. materialIridescenceIOR: materialIridescenceIOR,
  34571. materialIridescenceThickness: materialIridescenceThickness,
  34572. materialLightMap: materialLightMap,
  34573. materialLineDashOffset: materialLineDashOffset,
  34574. materialLineDashSize: materialLineDashSize,
  34575. materialLineGapSize: materialLineGapSize,
  34576. materialLineScale: materialLineScale,
  34577. materialLineWidth: materialLineWidth,
  34578. materialMetalness: materialMetalness,
  34579. materialNormal: materialNormal,
  34580. materialOpacity: materialOpacity,
  34581. materialPointSize: materialPointSize,
  34582. materialReference: materialReference,
  34583. materialReflectivity: materialReflectivity,
  34584. materialRefractionRatio: materialRefractionRatio,
  34585. materialRotation: materialRotation,
  34586. materialRoughness: materialRoughness,
  34587. materialSheen: materialSheen,
  34588. materialSheenRoughness: materialSheenRoughness,
  34589. materialShininess: materialShininess,
  34590. materialSpecular: materialSpecular,
  34591. materialSpecularColor: materialSpecularColor,
  34592. materialSpecularIntensity: materialSpecularIntensity,
  34593. materialSpecularStrength: materialSpecularStrength,
  34594. materialThickness: materialThickness,
  34595. materialTransmission: materialTransmission,
  34596. max: max$1,
  34597. maxMipLevel: maxMipLevel,
  34598. mediumpModelViewMatrix: mediumpModelViewMatrix,
  34599. metalness: metalness,
  34600. min: min$1,
  34601. mix: mix,
  34602. mixElement: mixElement,
  34603. mod: mod,
  34604. modelDirection: modelDirection,
  34605. modelNormalMatrix: modelNormalMatrix,
  34606. modelPosition: modelPosition,
  34607. modelRadius: modelRadius,
  34608. modelScale: modelScale,
  34609. modelViewMatrix: modelViewMatrix,
  34610. modelViewPosition: modelViewPosition,
  34611. modelViewProjection: modelViewProjection,
  34612. modelWorldMatrix: modelWorldMatrix,
  34613. modelWorldMatrixInverse: modelWorldMatrixInverse,
  34614. morphReference: morphReference,
  34615. mrt: mrt,
  34616. mul: mul,
  34617. mx_aastep: mx_aastep,
  34618. mx_add: mx_add,
  34619. mx_atan2: mx_atan2,
  34620. mx_cell_noise_float: mx_cell_noise_float,
  34621. mx_contrast: mx_contrast,
  34622. mx_divide: mx_divide,
  34623. mx_fractal_noise_float: mx_fractal_noise_float,
  34624. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  34625. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  34626. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  34627. mx_frame: mx_frame,
  34628. mx_heighttonormal: mx_heighttonormal,
  34629. mx_hsvtorgb: mx_hsvtorgb,
  34630. mx_ifequal: mx_ifequal,
  34631. mx_ifgreater: mx_ifgreater,
  34632. mx_ifgreatereq: mx_ifgreatereq,
  34633. mx_invert: mx_invert,
  34634. mx_modulo: mx_modulo,
  34635. mx_multiply: mx_multiply,
  34636. mx_noise_float: mx_noise_float,
  34637. mx_noise_vec3: mx_noise_vec3,
  34638. mx_noise_vec4: mx_noise_vec4,
  34639. mx_place2d: mx_place2d,
  34640. mx_power: mx_power,
  34641. mx_ramp4: mx_ramp4,
  34642. mx_ramplr: mx_ramplr,
  34643. mx_ramptb: mx_ramptb,
  34644. mx_rgbtohsv: mx_rgbtohsv,
  34645. mx_rotate2d: mx_rotate2d,
  34646. mx_rotate3d: mx_rotate3d,
  34647. mx_safepower: mx_safepower,
  34648. mx_separate: mx_separate,
  34649. mx_splitlr: mx_splitlr,
  34650. mx_splittb: mx_splittb,
  34651. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  34652. mx_subtract: mx_subtract,
  34653. mx_timer: mx_timer,
  34654. mx_transform_uv: mx_transform_uv,
  34655. mx_unifiednoise2d: mx_unifiednoise2d,
  34656. mx_unifiednoise3d: mx_unifiednoise3d,
  34657. mx_worley_noise_float: mx_worley_noise_float,
  34658. mx_worley_noise_vec2: mx_worley_noise_vec2,
  34659. mx_worley_noise_vec3: mx_worley_noise_vec3,
  34660. negate: negate,
  34661. negateOnBackSide: negateOnBackSide,
  34662. neutralToneMapping: neutralToneMapping,
  34663. nodeArray: nodeArray,
  34664. nodeImmutable: nodeImmutable,
  34665. nodeObject: nodeObject,
  34666. nodeObjectIntent: nodeObjectIntent,
  34667. nodeObjects: nodeObjects,
  34668. nodeProxy: nodeProxy,
  34669. nodeProxyConstructor: nodeProxyConstructor,
  34670. nodeProxyIntent: nodeProxyIntent,
  34671. normalFlat: normalFlat,
  34672. normalGeometry: normalGeometry,
  34673. normalLocal: normalLocal,
  34674. normalMap: normalMap,
  34675. normalView: normalView,
  34676. normalViewGeometry: normalViewGeometry,
  34677. normalWorld: normalWorld,
  34678. normalWorldGeometry: normalWorldGeometry,
  34679. normalize: normalize,
  34680. not: not,
  34681. notEqual: notEqual,
  34682. numWorkgroups: numWorkgroups,
  34683. objectDirection: objectDirection,
  34684. objectGroup: objectGroup,
  34685. objectPosition: objectPosition,
  34686. objectRadius: objectRadius,
  34687. objectScale: objectScale,
  34688. objectViewPosition: objectViewPosition,
  34689. objectWorldMatrix: objectWorldMatrix,
  34690. oneMinus: oneMinus,
  34691. or: or,
  34692. orthographicDepthToViewZ: orthographicDepthToViewZ,
  34693. oscSawtooth: oscSawtooth,
  34694. oscSine: oscSine,
  34695. oscSquare: oscSquare,
  34696. oscTriangle: oscTriangle,
  34697. output: output,
  34698. outputStruct: outputStruct,
  34699. overloadingFn: overloadingFn,
  34700. overrideNode: overrideNode,
  34701. overrideNodes: overrideNodes,
  34702. packHalf2x16: packHalf2x16,
  34703. packNormalToRGB: packNormalToRGB,
  34704. packSnorm2x16: packSnorm2x16,
  34705. packUnorm2x16: packUnorm2x16,
  34706. parabola: parabola,
  34707. parallaxDirection: parallaxDirection,
  34708. parallaxUV: parallaxUV,
  34709. parameter: parameter,
  34710. pass: pass,
  34711. passTexture: passTexture,
  34712. pcurve: pcurve,
  34713. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  34714. pmremTexture: pmremTexture,
  34715. pointShadow: pointShadow,
  34716. pointUV: pointUV,
  34717. pointWidth: pointWidth,
  34718. positionGeometry: positionGeometry,
  34719. positionLocal: positionLocal,
  34720. positionPrevious: positionPrevious,
  34721. positionView: positionView,
  34722. positionViewDirection: positionViewDirection,
  34723. positionWorld: positionWorld,
  34724. positionWorldDirection: positionWorldDirection,
  34725. posterize: posterize,
  34726. pow: pow,
  34727. pow2: pow2,
  34728. pow3: pow3,
  34729. pow4: pow4,
  34730. premultiplyAlpha: premultiplyAlpha,
  34731. property: property,
  34732. quadBroadcast: quadBroadcast,
  34733. quadSwapDiagonal: quadSwapDiagonal,
  34734. quadSwapX: quadSwapX,
  34735. quadSwapY: quadSwapY,
  34736. radians: radians,
  34737. rand: rand,
  34738. range: range,
  34739. rangeFogFactor: rangeFogFactor,
  34740. reciprocal: reciprocal,
  34741. reference: reference,
  34742. referenceBuffer: referenceBuffer,
  34743. reflect: reflect,
  34744. reflectVector: reflectVector,
  34745. reflectView: reflectView,
  34746. reflector: reflector,
  34747. refract: refract,
  34748. refractVector: refractVector,
  34749. refractView: refractView,
  34750. reinhardToneMapping: reinhardToneMapping,
  34751. remap: remap,
  34752. remapClamp: remapClamp,
  34753. renderGroup: renderGroup,
  34754. renderOutput: renderOutput,
  34755. rendererReference: rendererReference,
  34756. replaceDefaultUV: replaceDefaultUV,
  34757. rotate: rotate,
  34758. rotateUV: rotateUV,
  34759. roughness: roughness,
  34760. round: round,
  34761. rtt: rtt,
  34762. sRGBTransferEOTF: sRGBTransferEOTF,
  34763. sRGBTransferOETF: sRGBTransferOETF,
  34764. sample: sample,
  34765. sampler: sampler,
  34766. samplerComparison: samplerComparison,
  34767. saturate: saturate,
  34768. saturation: saturation,
  34769. screenCoordinate: screenCoordinate,
  34770. screenDPR: screenDPR,
  34771. screenSize: screenSize,
  34772. screenUV: screenUV,
  34773. select: select,
  34774. setCurrentStack: setCurrentStack,
  34775. setName: setName,
  34776. shaderStages: shaderStages,
  34777. shadow: shadow,
  34778. shadowPositionWorld: shadowPositionWorld,
  34779. shapeCircle: shapeCircle,
  34780. sharedUniformGroup: sharedUniformGroup,
  34781. sheen: sheen,
  34782. sheenRoughness: sheenRoughness,
  34783. shiftLeft: shiftLeft,
  34784. shiftRight: shiftRight,
  34785. shininess: shininess,
  34786. sign: sign,
  34787. sin: sin,
  34788. sinc: sinc,
  34789. sinh: sinh,
  34790. skinning: skinning,
  34791. smoothstep: smoothstep,
  34792. smoothstepElement: smoothstepElement,
  34793. specularColor: specularColor,
  34794. specularColorBlended: specularColorBlended,
  34795. specularF90: specularF90,
  34796. spherizeUV: spherizeUV,
  34797. split: split,
  34798. spritesheetUV: spritesheetUV,
  34799. sqrt: sqrt,
  34800. stack: stack,
  34801. step: step,
  34802. stepElement: stepElement,
  34803. storage: storage,
  34804. storageBarrier: storageBarrier,
  34805. storageTexture: storageTexture,
  34806. storageTexture3D: storageTexture3D,
  34807. struct: struct,
  34808. sub: sub,
  34809. subBuild: subBuild,
  34810. subgroupAdd: subgroupAdd,
  34811. subgroupAll: subgroupAll,
  34812. subgroupAnd: subgroupAnd,
  34813. subgroupAny: subgroupAny,
  34814. subgroupBallot: subgroupBallot,
  34815. subgroupBroadcast: subgroupBroadcast,
  34816. subgroupBroadcastFirst: subgroupBroadcastFirst,
  34817. subgroupElect: subgroupElect,
  34818. subgroupExclusiveAdd: subgroupExclusiveAdd,
  34819. subgroupExclusiveMul: subgroupExclusiveMul,
  34820. subgroupInclusiveAdd: subgroupInclusiveAdd,
  34821. subgroupInclusiveMul: subgroupInclusiveMul,
  34822. subgroupIndex: subgroupIndex,
  34823. subgroupMax: subgroupMax,
  34824. subgroupMin: subgroupMin,
  34825. subgroupMul: subgroupMul,
  34826. subgroupOr: subgroupOr,
  34827. subgroupShuffle: subgroupShuffle,
  34828. subgroupShuffleDown: subgroupShuffleDown,
  34829. subgroupShuffleUp: subgroupShuffleUp,
  34830. subgroupShuffleXor: subgroupShuffleXor,
  34831. subgroupSize: subgroupSize,
  34832. subgroupXor: subgroupXor,
  34833. tan: tan,
  34834. tangentGeometry: tangentGeometry,
  34835. tangentLocal: tangentLocal,
  34836. tangentView: tangentView,
  34837. tangentWorld: tangentWorld,
  34838. tanh: tanh,
  34839. texture: texture,
  34840. texture3D: texture3D,
  34841. texture3DLevel: texture3DLevel,
  34842. texture3DLoad: texture3DLoad,
  34843. textureBarrier: textureBarrier,
  34844. textureBicubic: textureBicubic,
  34845. textureBicubicLevel: textureBicubicLevel,
  34846. textureCubeUV: textureCubeUV,
  34847. textureLevel: textureLevel,
  34848. textureLoad: textureLoad,
  34849. textureSize: textureSize,
  34850. textureStore: textureStore,
  34851. thickness: thickness,
  34852. time: time,
  34853. toneMapping: toneMapping,
  34854. toneMappingExposure: toneMappingExposure,
  34855. toonOutlinePass: toonOutlinePass,
  34856. transformDirection: transformDirection,
  34857. transformNormal: transformNormal,
  34858. transformNormalByInverseViewMatrix: transformNormalByInverseViewMatrix,
  34859. transformNormalByViewMatrix: transformNormalByViewMatrix,
  34860. transformNormalToView: transformNormalToView,
  34861. transformedClearcoatNormalView: transformedClearcoatNormalView,
  34862. transformedNormalView: transformedNormalView,
  34863. transformedNormalWorld: transformedNormalWorld,
  34864. transmission: transmission,
  34865. transpose: transpose,
  34866. triNoise3D: triNoise3D,
  34867. triplanarTexture: triplanarTexture,
  34868. triplanarTextures: triplanarTextures,
  34869. trunc: trunc,
  34870. uint: uint,
  34871. uintBitsToFloat: uintBitsToFloat,
  34872. uniform: uniform,
  34873. uniformArray: uniformArray,
  34874. uniformCubeTexture: uniformCubeTexture,
  34875. uniformFlow: uniformFlow,
  34876. uniformGroup: uniformGroup,
  34877. uniformTexture: uniformTexture,
  34878. unpackHalf2x16: unpackHalf2x16,
  34879. unpackNormal: unpackNormal,
  34880. unpackRGBToNormal: unpackRGBToNormal,
  34881. unpackSnorm2x16: unpackSnorm2x16,
  34882. unpackUnorm2x16: unpackUnorm2x16,
  34883. unpremultiplyAlpha: unpremultiplyAlpha,
  34884. userData: userData,
  34885. uv: uv$1,
  34886. uvec2: uvec2,
  34887. uvec3: uvec3,
  34888. uvec4: uvec4,
  34889. varying: varying,
  34890. varyingProperty: varyingProperty,
  34891. vec2: vec2,
  34892. vec3: vec3,
  34893. vec4: vec4,
  34894. vectorComponents: vectorComponents,
  34895. velocity: velocity,
  34896. vertexColor: vertexColor,
  34897. vertexIndex: vertexIndex,
  34898. vertexStage: vertexStage,
  34899. vibrance: vibrance,
  34900. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  34901. viewZToOrthographicDepth: viewZToOrthographicDepth,
  34902. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  34903. viewZToReversedOrthographicDepth: viewZToReversedOrthographicDepth,
  34904. viewZToReversedPerspectiveDepth: viewZToReversedPerspectiveDepth,
  34905. viewport: viewport,
  34906. viewportCoordinate: viewportCoordinate,
  34907. viewportDepthTexture: viewportDepthTexture,
  34908. viewportLinearDepth: viewportLinearDepth,
  34909. viewportMipTexture: viewportMipTexture,
  34910. viewportOpaqueMipTexture: viewportOpaqueMipTexture,
  34911. viewportResolution: viewportResolution,
  34912. viewportSafeUV: viewportSafeUV,
  34913. viewportSharedTexture: viewportSharedTexture,
  34914. viewportSize: viewportSize,
  34915. viewportTexture: viewportTexture,
  34916. viewportUV: viewportUV,
  34917. vogelDiskSample: vogelDiskSample,
  34918. wgsl: wgsl,
  34919. wgslFn: wgslFn,
  34920. workgroupArray: workgroupArray,
  34921. workgroupBarrier: workgroupBarrier,
  34922. workgroupId: workgroupId,
  34923. workingToColorSpace: workingToColorSpace,
  34924. xor: xor
  34925. });
  34926. const _clearColor = /*@__PURE__*/ new Color4();
  34927. /**
  34928. * This renderer module manages the background.
  34929. *
  34930. * @private
  34931. * @augments DataMap
  34932. */
  34933. class Background extends DataMap {
  34934. /**
  34935. * Constructs a new background management component.
  34936. *
  34937. * @param {Renderer} renderer - The renderer.
  34938. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  34939. */
  34940. constructor( renderer, nodes ) {
  34941. super();
  34942. /**
  34943. * The renderer.
  34944. *
  34945. * @type {Renderer}
  34946. */
  34947. this.renderer = renderer;
  34948. /**
  34949. * Renderer component for managing nodes related logic.
  34950. *
  34951. * @type {NodeManager}
  34952. */
  34953. this.nodes = nodes;
  34954. }
  34955. /**
  34956. * Updates the background for the given scene. Depending on how `Scene.background`
  34957. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  34958. * or add a mesh to the render list for rendering the background as a textured plane
  34959. * or skybox.
  34960. *
  34961. * @param {Scene} scene - The scene.
  34962. * @param {RenderList} renderList - The current render list.
  34963. * @param {RenderContext} renderContext - The current render context.
  34964. */
  34965. update( scene, renderList, renderContext ) {
  34966. const renderer = this.renderer;
  34967. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  34968. let forceClear = false;
  34969. if ( background === null ) {
  34970. // no background settings, use clear color configuration from the renderer
  34971. renderer._clearColor.getRGB( _clearColor );
  34972. _clearColor.a = renderer._clearColor.a;
  34973. } else if ( background.isColor === true ) {
  34974. // background is an opaque color
  34975. background.getRGB( _clearColor );
  34976. _clearColor.a = 1;
  34977. forceClear = true;
  34978. } else if ( background.isNode === true ) {
  34979. const sceneData = this.get( scene );
  34980. const backgroundNode = background;
  34981. _clearColor.copy( renderer._clearColor );
  34982. let backgroundMesh = sceneData.backgroundMesh;
  34983. if ( backgroundMesh === undefined ) {
  34984. const backgroundMeshNode = vec4( backgroundNode ).mul( backgroundIntensity ).context( {
  34985. // @TODO: Add Texture2D support using node context
  34986. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  34987. getTextureLevel: () => backgroundBlurriness
  34988. } );
  34989. // when using orthographic cameras, we must scale the skybox sphere
  34990. // up to exceed the dimensions of the camera's viewing box.
  34991. const isOrtho = cameraProjectionMatrix.element( 3 ).element( 3 ).equal( 1.0 );
  34992. // calculate the orthographic scale
  34993. // projectionMatrix[1][1] is (1 / top). Invert it to get the height and multiply by 3.0
  34994. // (an arbitrary safety factor) to ensure the skybox is large enough to cover the corners
  34995. // of the rectangular screen
  34996. const orthoScale = div( 1.0, cameraProjectionMatrix.element( 1 ).element( 1 ) ).mul( 3.0 );
  34997. // compute vertex position
  34998. const modifiedPosition = isOrtho.select( positionLocal.mul( orthoScale ), positionLocal );
  34999. // by using a w component of 0, the skybox will not translate when the camera moves through the scene
  35000. const viewPosition = modelViewMatrix.mul( vec4( modifiedPosition, 0.0 ) );
  35001. // we force w=1.0 here to prevent the w_clip=0 divide-by-zero error for ortho cameras.
  35002. let viewProj = cameraProjectionMatrix.mul( vec4( viewPosition.xyz, 1.0 ) );
  35003. // force background to far plane so it does not occlude objects
  35004. viewProj = viewProj.setZ( viewProj.w );
  35005. const nodeMaterial = new NodeMaterial();
  35006. nodeMaterial.name = 'Background.material';
  35007. nodeMaterial.side = BackSide;
  35008. nodeMaterial.depthTest = false;
  35009. nodeMaterial.depthWrite = false;
  35010. nodeMaterial.allowOverride = false;
  35011. nodeMaterial.fog = false;
  35012. nodeMaterial.lights = false;
  35013. nodeMaterial.vertexNode = viewProj;
  35014. nodeMaterial.colorNode = backgroundMeshNode;
  35015. sceneData.backgroundMeshNode = backgroundMeshNode;
  35016. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  35017. backgroundMesh.frustumCulled = false;
  35018. backgroundMesh.name = 'Background.mesh';
  35019. function onBackgroundDispose() {
  35020. background.removeEventListener( 'dispose', onBackgroundDispose );
  35021. backgroundMesh.material.dispose();
  35022. backgroundMesh.geometry.dispose();
  35023. }
  35024. background.addEventListener( 'dispose', onBackgroundDispose );
  35025. }
  35026. const backgroundCacheKey = backgroundNode.getCacheKey();
  35027. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  35028. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  35029. sceneData.backgroundMeshNode.needsUpdate = true;
  35030. backgroundMesh.material.needsUpdate = true;
  35031. sceneData.backgroundCacheKey = backgroundCacheKey;
  35032. }
  35033. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  35034. } else {
  35035. error( 'Renderer: Unsupported background configuration.', background );
  35036. }
  35037. //
  35038. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  35039. if ( environmentBlendMode === 'additive' ) {
  35040. _clearColor.set( 0, 0, 0, 1 );
  35041. } else if ( environmentBlendMode === 'alpha-blend' ) {
  35042. _clearColor.set( 0, 0, 0, 0 );
  35043. }
  35044. //
  35045. if ( renderer.autoClear === true || forceClear === true ) {
  35046. const clearColorValue = renderContext.clearColorValue;
  35047. clearColorValue.r = _clearColor.r;
  35048. clearColorValue.g = _clearColor.g;
  35049. clearColorValue.b = _clearColor.b;
  35050. clearColorValue.a = _clearColor.a;
  35051. // premultiply alpha
  35052. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  35053. clearColorValue.r *= clearColorValue.a;
  35054. clearColorValue.g *= clearColorValue.a;
  35055. clearColorValue.b *= clearColorValue.a;
  35056. }
  35057. //
  35058. renderContext.depthClearValue = renderer.getClearDepth();
  35059. renderContext.stencilClearValue = renderer.getClearStencil();
  35060. renderContext.clearColor = renderer.autoClearColor === true;
  35061. renderContext.clearDepth = renderer.autoClearDepth === true;
  35062. renderContext.clearStencil = renderer.autoClearStencil === true;
  35063. } else {
  35064. renderContext.clearColor = false;
  35065. renderContext.clearDepth = false;
  35066. renderContext.clearStencil = false;
  35067. }
  35068. }
  35069. }
  35070. let _id$7 = 0;
  35071. /**
  35072. * A bind group represents a collection of bindings and thus a collection
  35073. * or resources. Bind groups are assigned to pipelines to provide them
  35074. * with the required resources (like uniform buffers or textures).
  35075. *
  35076. * @private
  35077. */
  35078. class BindGroup {
  35079. /**
  35080. * Constructs a new bind group.
  35081. *
  35082. * @param {string} name - The bind group's name.
  35083. * @param {Array<Binding>} bindings - An array of bindings.
  35084. * @param {number} index - The group index.
  35085. */
  35086. constructor( name = '', bindings = [] ) {
  35087. /**
  35088. * The bind group's name.
  35089. *
  35090. * @type {string}
  35091. */
  35092. this.name = name;
  35093. /**
  35094. * An array of bindings.
  35095. *
  35096. * @type {Array<Binding>}
  35097. */
  35098. this.bindings = bindings;
  35099. /**
  35100. * The group's ID.
  35101. *
  35102. * @type {number}
  35103. */
  35104. this.id = _id$7 ++;
  35105. }
  35106. }
  35107. /**
  35108. * This module represents the state of a node builder after it was
  35109. * used to build the nodes for a render object. The state holds the
  35110. * results of the build for further processing in the renderer.
  35111. *
  35112. * Render objects with identical cache keys share the same node builder state.
  35113. *
  35114. * @private
  35115. */
  35116. class NodeBuilderState {
  35117. /**
  35118. * Constructs a new node builder state.
  35119. *
  35120. * @param {string} vertexShader - The native vertex shader code.
  35121. * @param {string} fragmentShader - The native fragment shader code.
  35122. * @param {string} computeShader - The native compute shader code.
  35123. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  35124. * @param {Array<BindGroup>} bindings - An array of bind groups.
  35125. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  35126. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  35127. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  35128. * @param {NodeMaterialObserver} observer - A node material observer.
  35129. * @param {boolean} hardwareClipping - Whether the built material uses hardware clipping or not.
  35130. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  35131. */
  35132. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, hardwareClipping, transforms = [] ) {
  35133. /**
  35134. * The native vertex shader code.
  35135. *
  35136. * @type {string}
  35137. */
  35138. this.vertexShader = vertexShader;
  35139. /**
  35140. * The native fragment shader code.
  35141. *
  35142. * @type {string}
  35143. */
  35144. this.fragmentShader = fragmentShader;
  35145. /**
  35146. * The native compute shader code.
  35147. *
  35148. * @type {string}
  35149. */
  35150. this.computeShader = computeShader;
  35151. /**
  35152. * An array with transform attribute objects.
  35153. * Only relevant when using compute shaders with WebGL 2.
  35154. *
  35155. * @type {Array<Object>}
  35156. */
  35157. this.transforms = transforms;
  35158. /**
  35159. * An array of node attributes representing
  35160. * the attributes of the shaders.
  35161. *
  35162. * @type {Array<NodeAttribute>}
  35163. */
  35164. this.nodeAttributes = nodeAttributes;
  35165. /**
  35166. * An array of bind groups representing the uniform or storage
  35167. * buffers, texture or samplers of the shader.
  35168. *
  35169. * @type {Array<BindGroup>}
  35170. */
  35171. this.bindings = bindings;
  35172. /**
  35173. * An array of nodes that implement their `update()` method.
  35174. *
  35175. * @type {Array<Node>}
  35176. */
  35177. this.updateNodes = updateNodes;
  35178. /**
  35179. * An array of nodes that implement their `updateBefore()` method.
  35180. *
  35181. * @type {Array<Node>}
  35182. */
  35183. this.updateBeforeNodes = updateBeforeNodes;
  35184. /**
  35185. * An array of nodes that implement their `updateAfter()` method.
  35186. *
  35187. * @type {Array<Node>}
  35188. */
  35189. this.updateAfterNodes = updateAfterNodes;
  35190. /**
  35191. * A node material observer.
  35192. *
  35193. * @type {NodeMaterialObserver}
  35194. */
  35195. this.observer = observer;
  35196. /**
  35197. * Whether the built material uses hardware clipping or not.
  35198. *
  35199. * @type {boolean}
  35200. */
  35201. this.hardwareClipping = hardwareClipping;
  35202. /**
  35203. * How often this state is used by render objects.
  35204. *
  35205. * @type {number}
  35206. */
  35207. this.usedTimes = 0;
  35208. }
  35209. /**
  35210. * This method is used to create a array of bind groups based
  35211. * on the existing bind groups of this state. Shared groups are
  35212. * not cloned.
  35213. *
  35214. * @return {Array<BindGroup>} A array of bind groups.
  35215. */
  35216. createBindings() {
  35217. const bindings = [];
  35218. for ( const instanceGroup of this.bindings ) {
  35219. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  35220. if ( shared !== true ) {
  35221. const bindingsGroup = new BindGroup( instanceGroup.name, [] );
  35222. bindings.push( bindingsGroup );
  35223. for ( const instanceBinding of instanceGroup.bindings ) {
  35224. bindingsGroup.bindings.push( instanceBinding.clone() );
  35225. }
  35226. } else {
  35227. bindings.push( instanceGroup );
  35228. }
  35229. }
  35230. return bindings;
  35231. }
  35232. }
  35233. /**
  35234. * {@link NodeBuilder} is going to create instances of this class during the build process
  35235. * of nodes. They represent the final shader attributes that are going to be generated
  35236. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  35237. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  35238. */
  35239. class NodeAttribute {
  35240. /**
  35241. * Constructs a new node attribute.
  35242. *
  35243. * @param {string} name - The name of the attribute.
  35244. * @param {string} type - The type of the attribute.
  35245. * @param {?Node} node - An optional reference to the node.
  35246. */
  35247. constructor( name, type, node = null ) {
  35248. /**
  35249. * This flag can be used for type testing.
  35250. *
  35251. * @type {boolean}
  35252. * @readonly
  35253. * @default true
  35254. */
  35255. this.isNodeAttribute = true;
  35256. /**
  35257. * The name of the attribute.
  35258. *
  35259. * @type {string}
  35260. */
  35261. this.name = name;
  35262. /**
  35263. * The type of the attribute.
  35264. *
  35265. * @type {string}
  35266. */
  35267. this.type = type;
  35268. /**
  35269. * An optional reference to the node.
  35270. *
  35271. * @type {?Node}
  35272. * @default null
  35273. */
  35274. this.node = node;
  35275. }
  35276. }
  35277. /**
  35278. * {@link NodeBuilder} is going to create instances of this class during the build process
  35279. * of nodes. They represent the final shader uniforms that are going to be generated
  35280. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  35281. * for this purpose.
  35282. */
  35283. class NodeUniform {
  35284. /**
  35285. * Constructs a new node uniform.
  35286. *
  35287. * @param {string} name - The name of the uniform.
  35288. * @param {string} type - The type of the uniform.
  35289. * @param {UniformNode} node - An reference to the node.
  35290. */
  35291. constructor( name, type, node ) {
  35292. /**
  35293. * This flag can be used for type testing.
  35294. *
  35295. * @type {boolean}
  35296. * @readonly
  35297. * @default true
  35298. */
  35299. this.isNodeUniform = true;
  35300. /**
  35301. * The name of the uniform.
  35302. *
  35303. * @type {string}
  35304. */
  35305. this.name = name;
  35306. /**
  35307. * The type of the uniform.
  35308. *
  35309. * @type {string}
  35310. */
  35311. this.type = type;
  35312. /**
  35313. * An reference to the node.
  35314. *
  35315. * @type {UniformNode}
  35316. */
  35317. this.node = node;
  35318. }
  35319. /**
  35320. * The value of the uniform node.
  35321. *
  35322. * @type {any}
  35323. */
  35324. get value() {
  35325. return this.node.value;
  35326. }
  35327. set value( val ) {
  35328. this.node.value = val;
  35329. }
  35330. /**
  35331. * The id of the uniform node.
  35332. *
  35333. * @type {number}
  35334. */
  35335. get id() {
  35336. return this.node.id;
  35337. }
  35338. /**
  35339. * The uniform node's group.
  35340. *
  35341. * @type {UniformGroupNode}
  35342. */
  35343. get groupNode() {
  35344. return this.node.groupNode;
  35345. }
  35346. }
  35347. /**
  35348. * {@link NodeBuilder} is going to create instances of this class during the build process
  35349. * of nodes. They represent the final shader variables that are going to be generated
  35350. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  35351. * this purpose.
  35352. */
  35353. class NodeVar {
  35354. /**
  35355. * Constructs a new node variable.
  35356. *
  35357. * @param {string} name - The name of the variable.
  35358. * @param {string} type - The type of the variable.
  35359. * @param {boolean} [readOnly=false] - The read-only flag.
  35360. * @param {?number} [count=null] - The size.
  35361. */
  35362. constructor( name, type, readOnly = false, count = null ) {
  35363. /**
  35364. * This flag can be used for type testing.
  35365. *
  35366. * @type {boolean}
  35367. * @readonly
  35368. * @default true
  35369. */
  35370. this.isNodeVar = true;
  35371. /**
  35372. * The name of the variable.
  35373. *
  35374. * @type {string}
  35375. */
  35376. this.name = name;
  35377. /**
  35378. * The type of the variable.
  35379. *
  35380. * @type {string}
  35381. */
  35382. this.type = type;
  35383. /**
  35384. * The read-only flag.
  35385. *
  35386. * @type {boolean}
  35387. */
  35388. this.readOnly = readOnly;
  35389. /**
  35390. * The size.
  35391. *
  35392. * @type {?number}
  35393. */
  35394. this.count = count;
  35395. }
  35396. }
  35397. /**
  35398. * {@link NodeBuilder} is going to create instances of this class during the build process
  35399. * of nodes. They represent the final shader varyings that are going to be generated
  35400. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  35401. * this purpose.
  35402. *
  35403. * @augments NodeVar
  35404. */
  35405. class NodeVarying extends NodeVar {
  35406. /**
  35407. * Constructs a new node varying.
  35408. *
  35409. * @param {string} name - The name of the varying.
  35410. * @param {string} type - The type of the varying.
  35411. * @param {?string} interpolationType - The interpolation type of the varying.
  35412. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  35413. */
  35414. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  35415. super( name, type );
  35416. /**
  35417. * Whether this varying requires interpolation or not. This property can be used
  35418. * to check if the varying can be optimized for a variable.
  35419. *
  35420. * @type {boolean}
  35421. * @default false
  35422. */
  35423. this.needsInterpolation = false;
  35424. /**
  35425. * This flag can be used for type testing.
  35426. *
  35427. * @type {boolean}
  35428. * @readonly
  35429. * @default true
  35430. */
  35431. this.isNodeVarying = true;
  35432. /**
  35433. * The interpolation type of the varying data.
  35434. *
  35435. * @type {?string}
  35436. * @default null
  35437. */
  35438. this.interpolationType = interpolationType;
  35439. /**
  35440. * The interpolation sampling type of varying data.
  35441. *
  35442. * @type {?string}
  35443. * @default null
  35444. */
  35445. this.interpolationSampling = interpolationSampling;
  35446. }
  35447. }
  35448. /**
  35449. * {@link NodeBuilder} is going to create instances of this class during the build process
  35450. * of nodes. They represent user-defined, native shader code portions that are going to be
  35451. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  35452. * for this purpose.
  35453. */
  35454. class NodeCode {
  35455. /**
  35456. * Constructs a new code node.
  35457. *
  35458. * @param {string} name - The name of the code.
  35459. * @param {string} type - The node type.
  35460. * @param {string} [code=''] - The native shader code.
  35461. */
  35462. constructor( name, type, code = '' ) {
  35463. /**
  35464. * The name of the code.
  35465. *
  35466. * @type {string}
  35467. */
  35468. this.name = name;
  35469. /**
  35470. * The node type.
  35471. *
  35472. * @type {string}
  35473. */
  35474. this.type = type;
  35475. /**
  35476. * The native shader code.
  35477. *
  35478. * @type {string}
  35479. * @default ''
  35480. */
  35481. this.code = code;
  35482. Object.defineProperty( this, 'isNodeCode', { value: true } );
  35483. }
  35484. }
  35485. let _id$6 = 0;
  35486. /**
  35487. * This utility class is used in {@link NodeBuilder} as an internal
  35488. * cache data structure for node data.
  35489. */
  35490. class NodeCache {
  35491. /**
  35492. * Constructs a new node cache.
  35493. *
  35494. * @param {?NodeCache} parent - A reference to a parent cache.
  35495. */
  35496. constructor( parent = null ) {
  35497. /**
  35498. * The id of the cache.
  35499. *
  35500. * @type {number}
  35501. * @readonly
  35502. */
  35503. this.id = _id$6 ++;
  35504. /**
  35505. * A weak map for managing node data.
  35506. *
  35507. * @type {WeakMap<Node, Object>}
  35508. */
  35509. this.nodesData = new WeakMap();
  35510. /**
  35511. * Reference to a parent node cache.
  35512. *
  35513. * @type {?NodeCache}
  35514. * @default null
  35515. */
  35516. this.parent = parent;
  35517. }
  35518. /**
  35519. * Returns the data for the given node.
  35520. *
  35521. * @param {Node} node - The node.
  35522. * @return {?Object} The data for the node.
  35523. */
  35524. getData( node ) {
  35525. let data = this.nodesData.get( node );
  35526. if ( data === undefined && this.parent !== null ) {
  35527. data = this.parent.getData( node );
  35528. }
  35529. return data;
  35530. }
  35531. /**
  35532. * Sets the data for a given node.
  35533. *
  35534. * @param {Node} node - The node.
  35535. * @param {Object} data - The data that should be cached.
  35536. */
  35537. setData( node, data ) {
  35538. this.nodesData.set( node, data );
  35539. }
  35540. }
  35541. class StructType {
  35542. constructor( name, members ) {
  35543. this.name = name;
  35544. this.members = members;
  35545. this.output = false;
  35546. }
  35547. }
  35548. /**
  35549. * Abstract base class for uniforms.
  35550. *
  35551. * @abstract
  35552. * @private
  35553. */
  35554. class Uniform {
  35555. /**
  35556. * Constructs a new uniform.
  35557. *
  35558. * @param {string} name - The uniform's name.
  35559. * @param {any} value - The uniform's value.
  35560. */
  35561. constructor( name, value ) {
  35562. /**
  35563. * The uniform's name.
  35564. *
  35565. * @type {string}
  35566. */
  35567. this.name = name;
  35568. /**
  35569. * The uniform's value.
  35570. *
  35571. * @type {any}
  35572. */
  35573. this.value = value;
  35574. /**
  35575. * Used to build the uniform buffer according to the STD140 layout.
  35576. * Derived uniforms will set this property to a data type specific
  35577. * value.
  35578. *
  35579. * @type {number}
  35580. */
  35581. this.boundary = 0;
  35582. /**
  35583. * The item size. Derived uniforms will set this property to a data
  35584. * type specific value.
  35585. *
  35586. * @type {number}
  35587. */
  35588. this.itemSize = 0;
  35589. /**
  35590. * This property is set by {@link UniformsGroup} and marks
  35591. * the start position in the uniform buffer.
  35592. *
  35593. * @type {number}
  35594. */
  35595. this.offset = 0;
  35596. /**
  35597. * This property is set by {@link UniformsGroup} and marks
  35598. * the index position in the uniform array.
  35599. *
  35600. * @type {number}
  35601. */
  35602. this.index = -1;
  35603. }
  35604. /**
  35605. * Sets the uniform's value.
  35606. *
  35607. * @param {any} value - The value to set.
  35608. */
  35609. setValue( value ) {
  35610. this.value = value;
  35611. }
  35612. /**
  35613. * Returns the uniform's value.
  35614. *
  35615. * @return {any} The value.
  35616. */
  35617. getValue() {
  35618. return this.value;
  35619. }
  35620. }
  35621. /**
  35622. * Represents a Number uniform.
  35623. *
  35624. * @private
  35625. * @augments Uniform
  35626. */
  35627. class NumberUniform extends Uniform {
  35628. /**
  35629. * Constructs a new Number uniform.
  35630. *
  35631. * @param {string} name - The uniform's name.
  35632. * @param {number} value - The uniform's value.
  35633. */
  35634. constructor( name, value = 0 ) {
  35635. super( name, value );
  35636. /**
  35637. * This flag can be used for type testing.
  35638. *
  35639. * @type {boolean}
  35640. * @readonly
  35641. * @default true
  35642. */
  35643. this.isNumberUniform = true;
  35644. this.boundary = 4;
  35645. this.itemSize = 1;
  35646. }
  35647. }
  35648. /**
  35649. * Represents a Vector2 uniform.
  35650. *
  35651. * @private
  35652. * @augments Uniform
  35653. */
  35654. class Vector2Uniform extends Uniform {
  35655. /**
  35656. * Constructs a new Number uniform.
  35657. *
  35658. * @param {string} name - The uniform's name.
  35659. * @param {Vector2} value - The uniform's value.
  35660. */
  35661. constructor( name, value = new Vector2() ) {
  35662. super( name, value );
  35663. /**
  35664. * This flag can be used for type testing.
  35665. *
  35666. * @type {boolean}
  35667. * @readonly
  35668. * @default true
  35669. */
  35670. this.isVector2Uniform = true;
  35671. this.boundary = 8;
  35672. this.itemSize = 2;
  35673. }
  35674. }
  35675. /**
  35676. * Represents a Vector3 uniform.
  35677. *
  35678. * @private
  35679. * @augments Uniform
  35680. */
  35681. class Vector3Uniform extends Uniform {
  35682. /**
  35683. * Constructs a new Number uniform.
  35684. *
  35685. * @param {string} name - The uniform's name.
  35686. * @param {Vector3} value - The uniform's value.
  35687. */
  35688. constructor( name, value = new Vector3() ) {
  35689. super( name, value );
  35690. /**
  35691. * This flag can be used for type testing.
  35692. *
  35693. * @type {boolean}
  35694. * @readonly
  35695. * @default true
  35696. */
  35697. this.isVector3Uniform = true;
  35698. this.boundary = 16;
  35699. this.itemSize = 3;
  35700. }
  35701. }
  35702. /**
  35703. * Represents a Vector4 uniform.
  35704. *
  35705. * @private
  35706. * @augments Uniform
  35707. */
  35708. class Vector4Uniform extends Uniform {
  35709. /**
  35710. * Constructs a new Number uniform.
  35711. *
  35712. * @param {string} name - The uniform's name.
  35713. * @param {Vector4} value - The uniform's value.
  35714. */
  35715. constructor( name, value = new Vector4() ) {
  35716. super( name, value );
  35717. /**
  35718. * This flag can be used for type testing.
  35719. *
  35720. * @type {boolean}
  35721. * @readonly
  35722. * @default true
  35723. */
  35724. this.isVector4Uniform = true;
  35725. this.boundary = 16;
  35726. this.itemSize = 4;
  35727. }
  35728. }
  35729. /**
  35730. * Represents a Color uniform.
  35731. *
  35732. * @private
  35733. * @augments Uniform
  35734. */
  35735. class ColorUniform extends Uniform {
  35736. /**
  35737. * Constructs a new Number uniform.
  35738. *
  35739. * @param {string} name - The uniform's name.
  35740. * @param {Color} value - The uniform's value.
  35741. */
  35742. constructor( name, value = new Color() ) {
  35743. super( name, value );
  35744. /**
  35745. * This flag can be used for type testing.
  35746. *
  35747. * @type {boolean}
  35748. * @readonly
  35749. * @default true
  35750. */
  35751. this.isColorUniform = true;
  35752. this.boundary = 16;
  35753. this.itemSize = 3;
  35754. }
  35755. }
  35756. /**
  35757. * Represents a Matrix2 uniform.
  35758. *
  35759. * @private
  35760. * @augments Uniform
  35761. */
  35762. class Matrix2Uniform extends Uniform {
  35763. /**
  35764. * Constructs a new Number uniform.
  35765. *
  35766. * @param {string} name - The uniform's name.
  35767. * @param {Matrix2} value - The uniform's value.
  35768. */
  35769. constructor( name, value = new Matrix2() ) {
  35770. super( name, value );
  35771. /**
  35772. * This flag can be used for type testing.
  35773. *
  35774. * @type {boolean}
  35775. * @readonly
  35776. * @default true
  35777. */
  35778. this.isMatrix2Uniform = true;
  35779. this.boundary = 8;
  35780. this.itemSize = 4;
  35781. }
  35782. }
  35783. /**
  35784. * Represents a Matrix3 uniform.
  35785. *
  35786. * @private
  35787. * @augments Uniform
  35788. */
  35789. class Matrix3Uniform extends Uniform {
  35790. /**
  35791. * Constructs a new Number uniform.
  35792. *
  35793. * @param {string} name - The uniform's name.
  35794. * @param {Matrix3} value - The uniform's value.
  35795. */
  35796. constructor( name, value = new Matrix3() ) {
  35797. super( name, value );
  35798. /**
  35799. * This flag can be used for type testing.
  35800. *
  35801. * @type {boolean}
  35802. * @readonly
  35803. * @default true
  35804. */
  35805. this.isMatrix3Uniform = true;
  35806. this.boundary = 48;
  35807. this.itemSize = 12;
  35808. }
  35809. }
  35810. /**
  35811. * Represents a Matrix4 uniform.
  35812. *
  35813. * @private
  35814. * @augments Uniform
  35815. */
  35816. class Matrix4Uniform extends Uniform {
  35817. /**
  35818. * Constructs a new Number uniform.
  35819. *
  35820. * @param {string} name - The uniform's name.
  35821. * @param {Matrix4} value - The uniform's value.
  35822. */
  35823. constructor( name, value = new Matrix4() ) {
  35824. super( name, value );
  35825. /**
  35826. * This flag can be used for type testing.
  35827. *
  35828. * @type {boolean}
  35829. * @readonly
  35830. * @default true
  35831. */
  35832. this.isMatrix4Uniform = true;
  35833. this.boundary = 64;
  35834. this.itemSize = 16;
  35835. }
  35836. }
  35837. /**
  35838. * A special form of Number uniform binding type.
  35839. * It's value is managed by a node object.
  35840. *
  35841. * @private
  35842. * @augments NumberUniform
  35843. */
  35844. class NumberNodeUniform extends NumberUniform {
  35845. /**
  35846. * Constructs a new node-based Number uniform.
  35847. *
  35848. * @param {NodeUniform} nodeUniform - The node uniform.
  35849. */
  35850. constructor( nodeUniform ) {
  35851. super( nodeUniform.name, nodeUniform.value );
  35852. /**
  35853. * The node uniform.
  35854. *
  35855. * @type {NodeUniform}
  35856. */
  35857. this.nodeUniform = nodeUniform;
  35858. }
  35859. /**
  35860. * Overwritten to return the value of the node uniform.
  35861. *
  35862. * @return {number} The value.
  35863. */
  35864. getValue() {
  35865. return this.nodeUniform.value;
  35866. }
  35867. /**
  35868. * Returns the node uniform data type.
  35869. *
  35870. * @return {string} The data type.
  35871. */
  35872. getType() {
  35873. return this.nodeUniform.type;
  35874. }
  35875. }
  35876. /**
  35877. * A special form of Vector2 uniform binding type.
  35878. * It's value is managed by a node object.
  35879. *
  35880. * @private
  35881. * @augments Vector2Uniform
  35882. */
  35883. class Vector2NodeUniform extends Vector2Uniform {
  35884. /**
  35885. * Constructs a new node-based Vector2 uniform.
  35886. *
  35887. * @param {NodeUniform} nodeUniform - The node uniform.
  35888. */
  35889. constructor( nodeUniform ) {
  35890. super( nodeUniform.name, nodeUniform.value );
  35891. /**
  35892. * The node uniform.
  35893. *
  35894. * @type {NodeUniform}
  35895. */
  35896. this.nodeUniform = nodeUniform;
  35897. }
  35898. /**
  35899. * Overwritten to return the value of the node uniform.
  35900. *
  35901. * @return {Vector2} The value.
  35902. */
  35903. getValue() {
  35904. return this.nodeUniform.value;
  35905. }
  35906. /**
  35907. * Returns the node uniform data type.
  35908. *
  35909. * @return {string} The data type.
  35910. */
  35911. getType() {
  35912. return this.nodeUniform.type;
  35913. }
  35914. }
  35915. /**
  35916. * A special form of Vector3 uniform binding type.
  35917. * It's value is managed by a node object.
  35918. *
  35919. * @private
  35920. * @augments Vector3Uniform
  35921. */
  35922. class Vector3NodeUniform extends Vector3Uniform {
  35923. /**
  35924. * Constructs a new node-based Vector3 uniform.
  35925. *
  35926. * @param {NodeUniform} nodeUniform - The node uniform.
  35927. */
  35928. constructor( nodeUniform ) {
  35929. super( nodeUniform.name, nodeUniform.value );
  35930. /**
  35931. * The node uniform.
  35932. *
  35933. * @type {NodeUniform}
  35934. */
  35935. this.nodeUniform = nodeUniform;
  35936. }
  35937. /**
  35938. * Overwritten to return the value of the node uniform.
  35939. *
  35940. * @return {Vector3} The value.
  35941. */
  35942. getValue() {
  35943. return this.nodeUniform.value;
  35944. }
  35945. /**
  35946. * Returns the node uniform data type.
  35947. *
  35948. * @return {string} The data type.
  35949. */
  35950. getType() {
  35951. return this.nodeUniform.type;
  35952. }
  35953. }
  35954. /**
  35955. * A special form of Vector4 uniform binding type.
  35956. * It's value is managed by a node object.
  35957. *
  35958. * @private
  35959. * @augments Vector4Uniform
  35960. */
  35961. class Vector4NodeUniform extends Vector4Uniform {
  35962. /**
  35963. * Constructs a new node-based Vector4 uniform.
  35964. *
  35965. * @param {NodeUniform} nodeUniform - The node uniform.
  35966. */
  35967. constructor( nodeUniform ) {
  35968. super( nodeUniform.name, nodeUniform.value );
  35969. /**
  35970. * The node uniform.
  35971. *
  35972. * @type {NodeUniform}
  35973. */
  35974. this.nodeUniform = nodeUniform;
  35975. }
  35976. /**
  35977. * Overwritten to return the value of the node uniform.
  35978. *
  35979. * @return {Vector4} The value.
  35980. */
  35981. getValue() {
  35982. return this.nodeUniform.value;
  35983. }
  35984. /**
  35985. * Returns the node uniform data type.
  35986. *
  35987. * @return {string} The data type.
  35988. */
  35989. getType() {
  35990. return this.nodeUniform.type;
  35991. }
  35992. }
  35993. /**
  35994. * A special form of Color uniform binding type.
  35995. * It's value is managed by a node object.
  35996. *
  35997. * @private
  35998. * @augments ColorUniform
  35999. */
  36000. class ColorNodeUniform extends ColorUniform {
  36001. /**
  36002. * Constructs a new node-based Color uniform.
  36003. *
  36004. * @param {NodeUniform} nodeUniform - The node uniform.
  36005. */
  36006. constructor( nodeUniform ) {
  36007. super( nodeUniform.name, nodeUniform.value );
  36008. /**
  36009. * The node uniform.
  36010. *
  36011. * @type {NodeUniform}
  36012. */
  36013. this.nodeUniform = nodeUniform;
  36014. }
  36015. /**
  36016. * Overwritten to return the value of the node uniform.
  36017. *
  36018. * @return {Color} The value.
  36019. */
  36020. getValue() {
  36021. return this.nodeUniform.value;
  36022. }
  36023. /**
  36024. * Returns the node uniform data type.
  36025. *
  36026. * @return {string} The data type.
  36027. */
  36028. getType() {
  36029. return this.nodeUniform.type;
  36030. }
  36031. }
  36032. /**
  36033. * A special form of Matrix2 uniform binding type.
  36034. * It's value is managed by a node object.
  36035. *
  36036. * @private
  36037. * @augments Matrix2Uniform
  36038. */
  36039. class Matrix2NodeUniform extends Matrix2Uniform {
  36040. /**
  36041. * Constructs a new node-based Matrix2 uniform.
  36042. *
  36043. * @param {NodeUniform} nodeUniform - The node uniform.
  36044. */
  36045. constructor( nodeUniform ) {
  36046. super( nodeUniform.name, nodeUniform.value );
  36047. /**
  36048. * The node uniform.
  36049. *
  36050. * @type {NodeUniform}
  36051. */
  36052. this.nodeUniform = nodeUniform;
  36053. }
  36054. /**
  36055. * Overwritten to return the value of the node uniform.
  36056. *
  36057. * @return {Matrix2} The value.
  36058. */
  36059. getValue() {
  36060. return this.nodeUniform.value;
  36061. }
  36062. /**
  36063. * Returns the node uniform data type.
  36064. *
  36065. * @return {string} The data type.
  36066. */
  36067. getType() {
  36068. return this.nodeUniform.type;
  36069. }
  36070. }
  36071. /**
  36072. * A special form of Matrix3 uniform binding type.
  36073. * It's value is managed by a node object.
  36074. *
  36075. * @private
  36076. * @augments Matrix3Uniform
  36077. */
  36078. class Matrix3NodeUniform extends Matrix3Uniform {
  36079. /**
  36080. * Constructs a new node-based Matrix3 uniform.
  36081. *
  36082. * @param {NodeUniform} nodeUniform - The node uniform.
  36083. */
  36084. constructor( nodeUniform ) {
  36085. super( nodeUniform.name, nodeUniform.value );
  36086. /**
  36087. * The node uniform.
  36088. *
  36089. * @type {NodeUniform}
  36090. */
  36091. this.nodeUniform = nodeUniform;
  36092. }
  36093. /**
  36094. * Overwritten to return the value of the node uniform.
  36095. *
  36096. * @return {Matrix3} The value.
  36097. */
  36098. getValue() {
  36099. return this.nodeUniform.value;
  36100. }
  36101. /**
  36102. * Returns the node uniform data type.
  36103. *
  36104. * @return {string} The data type.
  36105. */
  36106. getType() {
  36107. return this.nodeUniform.type;
  36108. }
  36109. }
  36110. /**
  36111. * A special form of Matrix4 uniform binding type.
  36112. * It's value is managed by a node object.
  36113. *
  36114. * @private
  36115. * @augments Matrix4Uniform
  36116. */
  36117. class Matrix4NodeUniform extends Matrix4Uniform {
  36118. /**
  36119. * Constructs a new node-based Matrix4 uniform.
  36120. *
  36121. * @param {NodeUniform} nodeUniform - The node uniform.
  36122. */
  36123. constructor( nodeUniform ) {
  36124. super( nodeUniform.name, nodeUniform.value );
  36125. /**
  36126. * The node uniform.
  36127. *
  36128. * @type {NodeUniform}
  36129. */
  36130. this.nodeUniform = nodeUniform;
  36131. }
  36132. /**
  36133. * Overwritten to return the value of the node uniform.
  36134. *
  36135. * @return {Matrix4} The value.
  36136. */
  36137. getValue() {
  36138. return this.nodeUniform.value;
  36139. }
  36140. /**
  36141. * Returns the node uniform data type.
  36142. *
  36143. * @return {string} The data type.
  36144. */
  36145. getType() {
  36146. return this.nodeUniform.type;
  36147. }
  36148. }
  36149. let _id$5 = 0;
  36150. const _bindingGroupsCache = new WeakMap();
  36151. const _functionNodeCache = new WeakMap();
  36152. const sharedNodeData = new WeakMap();
  36153. const typeFromArray = new Map( [
  36154. [ Int8Array, 'int' ],
  36155. [ Int16Array, 'int' ],
  36156. [ Int32Array, 'int' ],
  36157. [ Uint8Array, 'uint' ],
  36158. [ Uint16Array, 'uint' ],
  36159. [ Uint32Array, 'uint' ],
  36160. [ Float32Array, 'float' ]
  36161. ] );
  36162. const _toFloat = ( value ) => {
  36163. if ( /e/g.test( value ) ) {
  36164. return String( value ).replace( /\+/g, '' );
  36165. } else {
  36166. value = Number( value );
  36167. return value + ( value % 1 ? '' : '.0' );
  36168. }
  36169. };
  36170. const _checkWriteUsage = ( data ) => {
  36171. if ( data.writeUsageCount > 0 ) return true;
  36172. if ( data.subBuildsCache !== undefined ) {
  36173. for ( const subBuild in data.subBuildsCache ) {
  36174. if ( _checkWriteUsage( data.subBuildsCache[ subBuild ] ) ) {
  36175. return true;
  36176. }
  36177. }
  36178. }
  36179. return false;
  36180. };
  36181. /**
  36182. * Base class for builders which generate a shader program based
  36183. * on a 3D object and its node material definition.
  36184. */
  36185. class NodeBuilder {
  36186. /**
  36187. * Constructs a new node builder.
  36188. *
  36189. * @param {Object3D} object - The 3D object.
  36190. * @param {Renderer} renderer - The current renderer.
  36191. * @param {NodeParser} parser - A reference to a node parser.
  36192. */
  36193. constructor( object, renderer, parser ) {
  36194. /**
  36195. * The 3D object.
  36196. *
  36197. * @type {Object3D}
  36198. */
  36199. this.object = object;
  36200. /**
  36201. * The material of the 3D object.
  36202. *
  36203. * @type {?Material}
  36204. */
  36205. this.material = ( object && object.material ) || null;
  36206. /**
  36207. * The geometry of the 3D object.
  36208. *
  36209. * @type {?BufferGeometry}
  36210. */
  36211. this.geometry = ( object && object.geometry ) || null;
  36212. /**
  36213. * The current renderer.
  36214. *
  36215. * @type {Renderer}
  36216. */
  36217. this.renderer = renderer;
  36218. /**
  36219. * A reference to a node parser.
  36220. *
  36221. * @type {NodeParser}
  36222. */
  36223. this.parser = parser;
  36224. /**
  36225. * The scene the 3D object belongs to.
  36226. *
  36227. * @type {?Scene}
  36228. * @default null
  36229. */
  36230. this.scene = null;
  36231. /**
  36232. * The camera the 3D object is rendered with.
  36233. *
  36234. * @type {?Camera}
  36235. * @default null
  36236. */
  36237. this.camera = null;
  36238. /**
  36239. * A list of all nodes the builder is processing
  36240. * for this 3D object.
  36241. *
  36242. * @type {Set<Node>}
  36243. */
  36244. this.nodes = new Set();
  36245. /**
  36246. * A list of all nodes the builder is processing in sequential order.
  36247. *
  36248. * This is used to determine the update order of nodes, which is important for
  36249. * {@link NodeUpdateType#UPDATE_BEFORE} and {@link NodeUpdateType#UPDATE_AFTER}.
  36250. *
  36251. * @type {Set<Node>}
  36252. */
  36253. this.sequentialNodes = new Set();
  36254. /**
  36255. * A list of all nodes which {@link Node#update} method should be executed.
  36256. *
  36257. * @type {Array<Node>}
  36258. */
  36259. this.updateNodes = [];
  36260. /**
  36261. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  36262. *
  36263. * @type {Array<Node>}
  36264. */
  36265. this.updateBeforeNodes = [];
  36266. /**
  36267. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  36268. *
  36269. * @type {Array<Node>}
  36270. */
  36271. this.updateAfterNodes = [];
  36272. /**
  36273. * A dictionary that assigns each node to a unique hash.
  36274. *
  36275. * @type {Object<number,Node>}
  36276. */
  36277. this.hashNodes = {};
  36278. /**
  36279. * A reference to a node material observer.
  36280. *
  36281. * @type {?NodeMaterialObserver}
  36282. * @default null
  36283. */
  36284. this.observer = null;
  36285. /**
  36286. * A reference to the current lights node.
  36287. *
  36288. * @type {?LightsNode}
  36289. * @default null
  36290. */
  36291. this.lightsNode = null;
  36292. /**
  36293. * A reference to the current environment node.
  36294. *
  36295. * @type {?Node}
  36296. * @default null
  36297. */
  36298. this.environmentNode = null;
  36299. /**
  36300. * A reference to the current fog node.
  36301. *
  36302. * @type {?Node}
  36303. * @default null
  36304. */
  36305. this.fogNode = null;
  36306. /**
  36307. * The current clipping context.
  36308. *
  36309. * @type {?ClippingContext}
  36310. */
  36311. this.clippingContext = null;
  36312. /**
  36313. * Whether the built material uses hardware clipping or not.
  36314. *
  36315. * @type {boolean}
  36316. * @default false
  36317. */
  36318. this.hardwareClipping = false;
  36319. /**
  36320. * The generated vertex shader.
  36321. *
  36322. * @type {?string}
  36323. */
  36324. this.vertexShader = null;
  36325. /**
  36326. * The generated fragment shader.
  36327. *
  36328. * @type {?string}
  36329. */
  36330. this.fragmentShader = null;
  36331. /**
  36332. * The generated compute shader.
  36333. *
  36334. * @type {?string}
  36335. */
  36336. this.computeShader = null;
  36337. /**
  36338. * Nodes used in the primary flow of code generation.
  36339. *
  36340. * @type {Object<string,Array<Node>>}
  36341. */
  36342. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  36343. /**
  36344. * Nodes code from `.flowNodes`.
  36345. *
  36346. * @type {Object<string,string>}
  36347. */
  36348. this.flowCode = { vertex: '', fragment: '', compute: '' };
  36349. /**
  36350. * This dictionary holds the node uniforms of the builder.
  36351. * The uniforms are maintained in an array for each shader stage.
  36352. *
  36353. * @type {Object}
  36354. */
  36355. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  36356. /**
  36357. * This dictionary holds the output structs of the builder.
  36358. * The structs are maintained in an array for each shader stage.
  36359. *
  36360. * @type {Object}
  36361. */
  36362. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  36363. /**
  36364. * This dictionary holds the types of the builder.
  36365. *
  36366. * @type {Object}
  36367. */
  36368. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  36369. /**
  36370. * This dictionary holds the bindings for each shader stage.
  36371. *
  36372. * @type {Object}
  36373. */
  36374. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  36375. /**
  36376. * This dictionary maintains the binding indices per bind group.
  36377. *
  36378. * @type {Object}
  36379. */
  36380. this.bindingsIndexes = {};
  36381. /**
  36382. * Reference to the array of bind groups.
  36383. *
  36384. * @type {?Array<BindGroup>}
  36385. */
  36386. this.bindGroups = null;
  36387. /**
  36388. * This array holds the node attributes of this builder
  36389. * created via {@link AttributeNode}.
  36390. *
  36391. * @type {Array<NodeAttribute>}
  36392. */
  36393. this.attributes = [];
  36394. /**
  36395. * This array holds the node attributes of this builder
  36396. * created via {@link BufferAttributeNode}.
  36397. *
  36398. * @type {Array<NodeAttribute>}
  36399. */
  36400. this.bufferAttributes = [];
  36401. /**
  36402. * This array holds the node varyings of this builder.
  36403. *
  36404. * @type {Array<NodeVarying>}
  36405. */
  36406. this.varyings = [];
  36407. /**
  36408. * This dictionary holds the (native) node codes of this builder.
  36409. * The codes are maintained in an array for each shader stage.
  36410. *
  36411. * @type {Object<string,Array<NodeCode>>}
  36412. */
  36413. this.codes = {};
  36414. /**
  36415. * This dictionary holds the node variables of this builder.
  36416. * The variables are maintained in an array for each shader stage.
  36417. * This dictionary is also used to count the number of variables
  36418. * according to their type (const, vars).
  36419. *
  36420. * @type {Object<string,Array<NodeVar>|number>}
  36421. */
  36422. this.vars = {};
  36423. /**
  36424. * This dictionary holds the declarations for each shader stage.
  36425. *
  36426. * @type {Object}
  36427. */
  36428. this.declarations = {};
  36429. /**
  36430. * Current code flow.
  36431. * All code generated in this stack will be stored in `.flow`.
  36432. *
  36433. * @type {{code: string}}
  36434. */
  36435. this.flow = { code: '' };
  36436. /**
  36437. * A chain of nodes.
  36438. * Used to check recursive calls in node-graph.
  36439. *
  36440. * @type {Array<Node>}
  36441. */
  36442. this.chaining = [];
  36443. /**
  36444. * The current stack.
  36445. * This reflects the current process in the code block hierarchy,
  36446. * it is useful to know if the current process is inside a conditional for example.
  36447. *
  36448. * @type {StackNode}
  36449. */
  36450. this.stack = stack();
  36451. /**
  36452. * List of stack nodes.
  36453. * The current stack hierarchy is stored in an array.
  36454. *
  36455. * @type {Array<StackNode>}
  36456. */
  36457. this.stacks = [];
  36458. /**
  36459. * A tab value. Used for shader string generation.
  36460. *
  36461. * @type {string}
  36462. * @default '\t'
  36463. */
  36464. this.tab = '\t';
  36465. /**
  36466. * Reference to the current function node.
  36467. *
  36468. * @type {?FunctionNode}
  36469. * @default null
  36470. */
  36471. this.currentFunctionNode = null;
  36472. /**
  36473. * The builder's context.
  36474. *
  36475. * @type {Object}
  36476. */
  36477. this.context = {
  36478. material: this.material
  36479. };
  36480. /**
  36481. * The builder's cache.
  36482. *
  36483. * @type {NodeCache}
  36484. */
  36485. this.cache = new NodeCache();
  36486. /**
  36487. * Since the {@link NodeBuilder#cache} might be temporarily
  36488. * overwritten by other caches, this member retains the reference
  36489. * to the builder's own cache.
  36490. *
  36491. * @type {NodeCache}
  36492. * @default this.cache
  36493. */
  36494. this.globalCache = this.cache;
  36495. this.flowsData = new WeakMap();
  36496. /**
  36497. * The current shader stage.
  36498. *
  36499. * @type {?('vertex'|'fragment'|'compute'|'any')}
  36500. */
  36501. this.shaderStage = null;
  36502. /**
  36503. * The current build stage.
  36504. *
  36505. * @type {?('setup'|'analyze'|'generate')}
  36506. */
  36507. this.buildStage = null;
  36508. /**
  36509. * The sub-build layers.
  36510. *
  36511. * @type {Array<SubBuildNode>}
  36512. * @default []
  36513. */
  36514. this.subBuildLayers = [];
  36515. /**
  36516. * The active stack nodes.
  36517. *
  36518. * @type {Array<StackNode>}
  36519. */
  36520. this.activeStacks = [];
  36521. /**
  36522. * The current sub-build TSL function(Fn).
  36523. *
  36524. * @type {?string}
  36525. * @default null
  36526. */
  36527. this.subBuildFn = null;
  36528. /**
  36529. * The current TSL function(Fn) call node.
  36530. *
  36531. * @type {?Node}
  36532. * @default null
  36533. */
  36534. this.fnCall = null;
  36535. Object.defineProperty( this, 'id', { value: _id$5 ++ } );
  36536. }
  36537. /**
  36538. * Whether the material is using flat shading or not.
  36539. *
  36540. * @returns {boolean} Whether the material is using flat shading or not.
  36541. */
  36542. isFlatShading() {
  36543. return this.material.flatShading === true || this.geometry.hasAttribute( 'normal' ) === false;
  36544. }
  36545. /**
  36546. * Whether the material is opaque or not.
  36547. *
  36548. * @return {boolean} Whether the material is opaque or not.
  36549. */
  36550. isOpaque() {
  36551. const material = this.material;
  36552. return material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false;
  36553. }
  36554. /**
  36555. * Factory method for creating an instance of {@link RenderTarget} with the given
  36556. * dimensions and options.
  36557. *
  36558. * @param {number} width - The width of the render target.
  36559. * @param {number} height - The height of the render target.
  36560. * @param {Object} options - The options of the render target.
  36561. * @return {RenderTarget} The render target.
  36562. */
  36563. createRenderTarget( width, height, options ) {
  36564. return new RenderTarget( width, height, options );
  36565. }
  36566. /**
  36567. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  36568. * dimensions and options.
  36569. *
  36570. * @param {number} size - The size of the cube render target.
  36571. * @param {Object} options - The options of the cube render target.
  36572. * @return {CubeRenderTarget} The cube render target.
  36573. */
  36574. createCubeRenderTarget( size, options ) {
  36575. return new CubeRenderTarget( size, options );
  36576. }
  36577. /**
  36578. * Whether the given node is included in the internal array of nodes or not.
  36579. *
  36580. * @param {Node} node - The node to test.
  36581. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  36582. */
  36583. includes( node ) {
  36584. return this.nodes.has( node );
  36585. }
  36586. /**
  36587. * Returns the type of the color output based on the renderer's render target.
  36588. *
  36589. * @param {number} [index=0] - The index of the render target texture.
  36590. * @return {string} The type.
  36591. */
  36592. getOutputType( index = 0 ) {
  36593. let type = 'vec4';
  36594. const renderTarget = this.renderer.getRenderTarget();
  36595. if ( renderTarget !== null ) {
  36596. const renderTargetType = renderTarget.textures[ index ].type;
  36597. const renderTargetFormat = renderTarget.textures[ index ].format;
  36598. let typeStr = 'vec';
  36599. if ( renderTargetType === IntType ) {
  36600. typeStr = 'ivec';
  36601. } else if ( renderTargetType === UnsignedIntType ) {
  36602. typeStr = 'uvec';
  36603. }
  36604. if ( renderTargetFormat === RedFormat || renderTargetFormat === RedIntegerFormat ) {
  36605. if ( renderTargetType === IntType ) type = 'int';
  36606. else if ( renderTargetType === UnsignedIntType ) type = 'uint';
  36607. else type = 'float';
  36608. } else if ( renderTargetFormat === RGFormat || renderTargetFormat === RGIntegerFormat ) {
  36609. type = `${ typeStr }2`;
  36610. } else if ( renderTargetFormat === RGBFormat || renderTargetFormat === RGBIntegerFormat ) {
  36611. type = `${ typeStr }3`;
  36612. } else {
  36613. type = `${ typeStr }4`;
  36614. }
  36615. }
  36616. return type;
  36617. }
  36618. /**
  36619. * Returns the output struct name which is required by
  36620. * {@link OutputStructNode}.
  36621. *
  36622. * @abstract
  36623. * @return {string} The name of the output struct.
  36624. */
  36625. getOutputStructName() {}
  36626. /**
  36627. * Returns a bind group for the given group name and binding.
  36628. *
  36629. * @private
  36630. * @param {string} groupName - The group name.
  36631. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  36632. * @return {BindGroup} The bind group
  36633. */
  36634. _getBindGroup( groupName, bindings ) {
  36635. const groupNode = bindings[ 0 ].groupNode;
  36636. let sharedGroup = groupNode.shared;
  36637. if ( sharedGroup ) {
  36638. for ( let i = 1; i < bindings.length; i ++ ) {
  36639. if ( groupNode !== bindings[ i ].groupNode ) {
  36640. sharedGroup = false;
  36641. }
  36642. }
  36643. }
  36644. //
  36645. let bindGroup;
  36646. if ( sharedGroup ) {
  36647. let cacheKeyString = '';
  36648. for ( const binding of bindings ) {
  36649. if ( binding.isNodeUniformsGroup ) {
  36650. binding.uniforms.sort( ( a, b ) => a.nodeUniform.node.id - b.nodeUniform.node.id );
  36651. for ( const uniform of binding.uniforms ) {
  36652. cacheKeyString += uniform.nodeUniform.node.id;
  36653. }
  36654. } else {
  36655. cacheKeyString += binding.nodeUniform.id;
  36656. }
  36657. }
  36658. // TODO: Remove this hack ._currentRenderContext
  36659. const currentContext = this.renderer._currentRenderContext || this.renderer; // use renderer as fallback until we have a compute context
  36660. let bindingGroupsCache = _bindingGroupsCache.get( currentContext );
  36661. if ( bindingGroupsCache === undefined ) {
  36662. bindingGroupsCache = new Map();
  36663. _bindingGroupsCache.set( currentContext, bindingGroupsCache );
  36664. }
  36665. //
  36666. const cacheKey = hashString( cacheKeyString );
  36667. bindGroup = bindingGroupsCache.get( cacheKey );
  36668. if ( bindGroup === undefined ) {
  36669. bindGroup = new BindGroup( groupName, bindings );
  36670. bindingGroupsCache.set( cacheKey, bindGroup );
  36671. }
  36672. } else {
  36673. bindGroup = new BindGroup( groupName, bindings );
  36674. }
  36675. return bindGroup;
  36676. }
  36677. /**
  36678. * Returns an array of node uniform groups for the given group name and shader stage.
  36679. *
  36680. * @param {string} groupName - The group name.
  36681. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36682. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  36683. */
  36684. getBindGroupArray( groupName, shaderStage ) {
  36685. const bindings = this.bindings[ shaderStage ];
  36686. let bindGroup = bindings[ groupName ];
  36687. if ( bindGroup === undefined ) {
  36688. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  36689. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  36690. }
  36691. bindings[ groupName ] = bindGroup = [];
  36692. }
  36693. return bindGroup;
  36694. }
  36695. /**
  36696. * Returns a list bindings of all shader stages separated by groups.
  36697. *
  36698. * @return {Array<BindGroup>} The list of bindings.
  36699. */
  36700. getBindings() {
  36701. let bindingsGroups = this.bindGroups;
  36702. if ( bindingsGroups === null ) {
  36703. const groups = {};
  36704. const bindings = this.bindings;
  36705. for ( const shaderStage of shaderStages ) {
  36706. for ( const groupName in bindings[ shaderStage ] ) {
  36707. const uniforms = bindings[ shaderStage ][ groupName ];
  36708. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  36709. for ( const uniform of uniforms ) {
  36710. if ( groupUniforms.includes( uniform ) === false ) {
  36711. groupUniforms.push( uniform );
  36712. }
  36713. }
  36714. }
  36715. }
  36716. bindingsGroups = [];
  36717. for ( const groupName in groups ) {
  36718. const group = groups[ groupName ];
  36719. const bindingsGroup = this._getBindGroup( groupName, group );
  36720. bindingsGroups.push( bindingsGroup );
  36721. }
  36722. this.bindGroups = bindingsGroups;
  36723. }
  36724. return bindingsGroups;
  36725. }
  36726. /**
  36727. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  36728. */
  36729. sortBindingGroups() {
  36730. const bindingsGroups = this.getBindings();
  36731. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  36732. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  36733. const bindingGroup = bindingsGroups[ i ];
  36734. this.bindingsIndexes[ bindingGroup.name ].group = i;
  36735. }
  36736. }
  36737. /**
  36738. * The builder maintains each node in a hash-based dictionary.
  36739. * This method sets the given node (value) with the given hash (key) into this dictionary.
  36740. *
  36741. * @param {Node} node - The node to add.
  36742. * @param {number} hash - The hash of the node.
  36743. */
  36744. setHashNode( node, hash ) {
  36745. this.hashNodes[ hash ] = node;
  36746. }
  36747. /**
  36748. * Adds a node to this builder.
  36749. *
  36750. * @param {Node} node - The node to add.
  36751. */
  36752. addNode( node ) {
  36753. if ( this.nodes.has( node ) === false ) {
  36754. this.nodes.add( node );
  36755. this.setHashNode( node, node.getHash( this ) );
  36756. }
  36757. }
  36758. /**
  36759. * It is used to add Nodes that will be used as FRAME and RENDER events,
  36760. * and need to follow a certain sequence in the calls to work correctly.
  36761. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  36762. *
  36763. * @param {Node} node - The node to add.
  36764. */
  36765. addSequentialNode( node ) {
  36766. const updateBeforeType = node.getUpdateBeforeType();
  36767. const updateAfterType = node.getUpdateAfterType();
  36768. if ( updateBeforeType !== NodeUpdateType.NONE || updateAfterType !== NodeUpdateType.NONE ) {
  36769. this.sequentialNodes.add( node );
  36770. }
  36771. }
  36772. /**
  36773. * Checks the update types of nodes
  36774. */
  36775. buildUpdateNodes() {
  36776. for ( const node of this.nodes ) {
  36777. const updateType = node.getUpdateType();
  36778. if ( updateType !== NodeUpdateType.NONE ) {
  36779. this.updateNodes.push( node );
  36780. }
  36781. }
  36782. for ( const node of this.sequentialNodes ) {
  36783. const updateBeforeType = node.getUpdateBeforeType();
  36784. const updateAfterType = node.getUpdateAfterType();
  36785. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  36786. this.updateBeforeNodes.push( node );
  36787. }
  36788. if ( updateAfterType !== NodeUpdateType.NONE ) {
  36789. this.updateAfterNodes.push( node );
  36790. }
  36791. }
  36792. }
  36793. /**
  36794. * A reference the current node which is the
  36795. * last node in the chain of nodes.
  36796. *
  36797. * @type {Node}
  36798. */
  36799. get currentNode() {
  36800. return this.chaining[ this.chaining.length - 1 ];
  36801. }
  36802. /**
  36803. * Whether the given texture is filtered or not.
  36804. *
  36805. * @param {Texture} texture - The texture to check.
  36806. * @return {boolean} Whether the given texture is filtered or not.
  36807. */
  36808. isFilteredTexture( texture ) {
  36809. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  36810. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  36811. }
  36812. /**
  36813. * Returns the maximum number of bytes available for uniform buffers.
  36814. *
  36815. * @return {number} The maximum number of bytes available for uniform buffers.
  36816. */
  36817. getUniformBufferLimit() {
  36818. return this.renderer.backend.capabilities.getUniformBufferLimit();
  36819. }
  36820. /**
  36821. * Adds the given node to the internal node chain.
  36822. * This is used to check recursive calls in node-graph.
  36823. *
  36824. * @param {Node} node - The node to add.
  36825. */
  36826. addChain( node ) {
  36827. /*
  36828. if ( this.chaining.indexOf( node ) !== - 1 ) {
  36829. warn( 'Recursive node: ', node );
  36830. }
  36831. */
  36832. this.chaining.push( node );
  36833. }
  36834. /**
  36835. * Removes the given node from the internal node chain.
  36836. *
  36837. * @param {Node} node - The node to remove.
  36838. */
  36839. removeChain( node ) {
  36840. const lastChain = this.chaining.pop();
  36841. if ( lastChain !== node ) {
  36842. throw new Error( 'THREE.NodeBuilder: Invalid node chaining!' );
  36843. }
  36844. }
  36845. /**
  36846. * Returns the native shader method name for a given generic name. E.g.
  36847. * the method name `textureDimensions` matches the WGSL name but must be
  36848. * resolved to `textureSize` in GLSL.
  36849. *
  36850. * @abstract
  36851. * @param {string} method - The method name to resolve.
  36852. * @return {string} The resolved method name.
  36853. */
  36854. getMethod( method ) {
  36855. return method;
  36856. }
  36857. /**
  36858. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  36859. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  36860. *
  36861. * @abstract
  36862. * @param {string} condSnippet - The condition determining which expression gets resolved.
  36863. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  36864. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  36865. * @return {string} The resolved method name.
  36866. */
  36867. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  36868. return null;
  36869. }
  36870. /**
  36871. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  36872. *
  36873. * @param {number} hash - The hash of the node.
  36874. * @return {Node} The found node.
  36875. */
  36876. getNodeFromHash( hash ) {
  36877. return this.hashNodes[ hash ];
  36878. }
  36879. /**
  36880. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  36881. *
  36882. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  36883. * @param {Node} node - The node to add.
  36884. * @return {Node} The node.
  36885. */
  36886. addFlow( shaderStage, node ) {
  36887. this.flowNodes[ shaderStage ].push( node );
  36888. return node;
  36889. }
  36890. /**
  36891. * Sets builder's context.
  36892. *
  36893. * @param {Object} context - The context to set.
  36894. */
  36895. setContext( context ) {
  36896. this.context = context;
  36897. }
  36898. /**
  36899. * Returns the builder's current context.
  36900. *
  36901. * @return {Object} The builder's current context.
  36902. */
  36903. getContext() {
  36904. return this.context;
  36905. }
  36906. /**
  36907. * Adds context data to the builder's current context.
  36908. *
  36909. * @param {Object} context - The context to add.
  36910. * @return {Object} The previous context.
  36911. */
  36912. addContext( context ) {
  36913. const previousContext = this.getContext();
  36914. this.setContext( { ...this.context, ...context } );
  36915. return previousContext;
  36916. }
  36917. /**
  36918. * Gets a context used in shader construction that can be shared across different materials.
  36919. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  36920. *
  36921. * @return {Object} The builder's current context without material.
  36922. */
  36923. getSharedContext() {
  36924. const context = { ...this.context };
  36925. delete context.material;
  36926. delete context.getUV;
  36927. delete context.getOutput;
  36928. delete context.getTextureLevel;
  36929. delete context.getAO;
  36930. delete context.getShadow;
  36931. return context;
  36932. }
  36933. /**
  36934. * Sets builder's cache.
  36935. *
  36936. * @param {NodeCache} cache - The cache to set.
  36937. */
  36938. setCache( cache ) {
  36939. this.cache = cache;
  36940. }
  36941. /**
  36942. * Returns the builder's current cache.
  36943. *
  36944. * @return {NodeCache} The builder's current cache.
  36945. */
  36946. getCache() {
  36947. return this.cache;
  36948. }
  36949. /**
  36950. * Returns a cache for the given node.
  36951. *
  36952. * @param {Node} node - The node.
  36953. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  36954. * @return {NodeCache} The cache.
  36955. */
  36956. getCacheFromNode( node, parent = true ) {
  36957. const data = this.getDataFromNode( node );
  36958. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  36959. return data.cache;
  36960. }
  36961. /**
  36962. * Whether the requested feature is available or not.
  36963. *
  36964. * @abstract
  36965. * @param {string} name - The requested feature.
  36966. * @return {boolean} Whether the requested feature is supported or not.
  36967. */
  36968. isAvailable( /*name*/ ) {
  36969. return false;
  36970. }
  36971. /**
  36972. * Returns the vertexIndex input variable as a native shader string.
  36973. *
  36974. * @abstract
  36975. * @return {string} The instanceIndex shader string.
  36976. */
  36977. getVertexIndex() {
  36978. warn( 'Abstract function.' );
  36979. }
  36980. /**
  36981. * Contextually returns either the vertex stage instance index builtin
  36982. * or the linearized index of an compute invocation within a grid of workgroups.
  36983. *
  36984. * @abstract
  36985. * @return {string} The instanceIndex shader string.
  36986. */
  36987. getInstanceIndex() {
  36988. warn( 'Abstract function.' );
  36989. }
  36990. /**
  36991. * Returns the drawIndex input variable as a native shader string.
  36992. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  36993. *
  36994. * @abstract
  36995. * @return {?string} The drawIndex shader string.
  36996. */
  36997. getDrawIndex() {
  36998. warn( 'Abstract function.' );
  36999. }
  37000. /**
  37001. * Returns the frontFacing input variable as a native shader string.
  37002. *
  37003. * @abstract
  37004. * @return {string} The frontFacing shader string.
  37005. */
  37006. getFrontFacing() {
  37007. warn( 'Abstract function.' );
  37008. }
  37009. /**
  37010. * Returns the fragCoord input variable as a native shader string.
  37011. *
  37012. * @abstract
  37013. * @return {string} The fragCoord shader string.
  37014. */
  37015. getFragCoord() {
  37016. warn( 'Abstract function.' );
  37017. }
  37018. /**
  37019. * Whether to flip texture data along its vertical axis or not. WebGL needs
  37020. * this method evaluate to `true`, WebGPU to `false`.
  37021. *
  37022. * @abstract
  37023. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  37024. */
  37025. isFlipY() {
  37026. return false;
  37027. }
  37028. /**
  37029. * Returns whether the builder is currently in an assignment context.
  37030. *
  37031. * @return {boolean} Whether the builder is in an assignment context.
  37032. */
  37033. isContextAssign() {
  37034. return this.context.assign === true;
  37035. }
  37036. /**
  37037. * Calling this method increases the usage count for the given node by one.
  37038. *
  37039. * @param {Node} node - The node to increase the usage count for.
  37040. * @return {number} The updated usage count.
  37041. */
  37042. increaseUsage( node ) {
  37043. const nodeData = this.getDataFromNode( node );
  37044. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  37045. if ( this.isContextAssign() ) {
  37046. nodeData.writeUsageCount = nodeData.writeUsageCount === undefined ? 1 : nodeData.writeUsageCount + 1;
  37047. } else {
  37048. nodeData.readUsageCount = nodeData.readUsageCount === undefined ? 1 : nodeData.readUsageCount + 1;
  37049. }
  37050. return nodeData.usageCount;
  37051. }
  37052. /**
  37053. * Returns whether the given node has been written to in any shader stage.
  37054. *
  37055. * @param {Node} node - The node to check.
  37056. * @return {boolean} Whether the node has been written to.
  37057. */
  37058. hasWriteUsage( node ) {
  37059. const refNode = node.getShared( this );
  37060. const cache = refNode.isGlobal( this ) ? this.globalCache : this.cache;
  37061. const nodeData = cache.getData( refNode );
  37062. if ( nodeData !== undefined ) {
  37063. for ( const shaderStage in nodeData ) {
  37064. if ( _checkWriteUsage( nodeData[ shaderStage ] ) ) {
  37065. return true;
  37066. }
  37067. }
  37068. }
  37069. return false;
  37070. }
  37071. /**
  37072. * Generates a texture sample shader string for the given texture data.
  37073. *
  37074. * @abstract
  37075. * @param {Texture} texture - The texture.
  37076. * @param {string} textureProperty - The texture property name.
  37077. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  37078. * @return {string} The generated shader string.
  37079. */
  37080. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  37081. warn( 'Abstract function.' );
  37082. }
  37083. /**
  37084. * Generates a texture LOD shader string for the given texture data.
  37085. *
  37086. * @abstract
  37087. * @param {Texture} texture - The texture.
  37088. * @param {string} textureProperty - The texture property name.
  37089. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  37090. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  37091. * @param {string} levelSnippet - Snippet defining the mip level.
  37092. * @return {string} The generated shader string.
  37093. */
  37094. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  37095. warn( 'Abstract function.' );
  37096. }
  37097. /**
  37098. * Generates the array declaration string.
  37099. *
  37100. * @param {string} type - The type.
  37101. * @param {?number} [count] - The count.
  37102. * @return {string} The generated value as a shader string.
  37103. */
  37104. generateArrayDeclaration( type, count ) {
  37105. return this.getType( type ) + '[ ' + count + ' ]';
  37106. }
  37107. /**
  37108. * Generates the array shader string for the given type and value.
  37109. *
  37110. * @param {string} type - The type.
  37111. * @param {?number} [count] - The count.
  37112. * @param {?Array<Node>} [values=null] - The default values.
  37113. * @return {string} The generated value as a shader string.
  37114. */
  37115. generateArray( type, count, values = null ) {
  37116. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  37117. for ( let i = 0; i < count; i ++ ) {
  37118. const value = values ? values[ i ] : null;
  37119. if ( value !== null ) {
  37120. snippet += value.build( this, type );
  37121. } else {
  37122. snippet += this.generateConst( type );
  37123. }
  37124. if ( i < count - 1 ) snippet += ', ';
  37125. }
  37126. snippet += ' )';
  37127. return snippet;
  37128. }
  37129. /**
  37130. * Generates the struct shader string.
  37131. *
  37132. * @param {string} type - The type.
  37133. * @param {Array<Object>} [membersLayout] - The count.
  37134. * @param {?Array<Node>} [values=null] - The default values.
  37135. * @return {string} The generated value as a shader string.
  37136. */
  37137. generateStruct( type, membersLayout, values = null ) {
  37138. const snippets = [];
  37139. for ( const member of membersLayout ) {
  37140. const { name, type } = member;
  37141. if ( values && values[ name ] && values[ name ].isNode ) {
  37142. snippets.push( values[ name ].build( this, type ) );
  37143. } else {
  37144. snippets.push( this.generateConst( type ) );
  37145. }
  37146. }
  37147. return type + '( ' + snippets.join( ', ' ) + ' )';
  37148. }
  37149. /**
  37150. * Generates the shader string for the given type and value.
  37151. *
  37152. * @param {string} type - The type.
  37153. * @param {?any} [value=null] - The value.
  37154. * @return {string} The generated value as a shader string.
  37155. */
  37156. generateConst( type, value = null ) {
  37157. if ( value === null ) {
  37158. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  37159. else if ( type === 'bool' ) value = false;
  37160. else if ( type === 'color' ) value = new Color();
  37161. else if ( type === 'vec2' || type === 'uvec2' || type === 'ivec2' ) value = new Vector2();
  37162. else if ( type === 'vec3' || type === 'uvec3' || type === 'ivec3' ) value = new Vector3();
  37163. else if ( type === 'vec4' || type === 'uvec4' || type === 'ivec4' ) value = new Vector4();
  37164. }
  37165. if ( type === 'float' ) return _toFloat( value );
  37166. if ( type === 'int' ) return `${ Math.round( value ) }`;
  37167. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  37168. if ( type === 'bool' ) return value ? 'true' : 'false';
  37169. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ _toFloat( value.r ) }, ${ _toFloat( value.g ) }, ${ _toFloat( value.b ) } )`;
  37170. const typeLength = this.getTypeLength( type );
  37171. const componentType = this.getComponentType( type );
  37172. const generateConst = value => this.generateConst( componentType, value );
  37173. if ( typeLength === 2 ) {
  37174. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  37175. } else if ( typeLength === 3 ) {
  37176. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  37177. } else if ( typeLength === 4 && type !== 'mat2' ) {
  37178. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  37179. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  37180. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  37181. } else if ( typeLength > 4 ) {
  37182. return `${ this.getType( type ) }()`;
  37183. }
  37184. throw new Error( `THREE.NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  37185. }
  37186. /**
  37187. * It might be necessary to convert certain data types to different ones
  37188. * so this method can be used to hide the conversion.
  37189. *
  37190. * @param {string} type - The type.
  37191. * @return {string} The updated type.
  37192. */
  37193. getType( type ) {
  37194. if ( type === 'color' ) return 'vec3';
  37195. return type;
  37196. }
  37197. /**
  37198. * Whether the given attribute name is defined in the geometry or not.
  37199. *
  37200. * @param {string} name - The attribute name.
  37201. * @return {boolean} Whether the given attribute name is defined in the geometry.
  37202. */
  37203. hasGeometryAttribute( name ) {
  37204. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  37205. }
  37206. /**
  37207. * Returns a node attribute for the given name and type.
  37208. *
  37209. * @param {string} name - The attribute's name.
  37210. * @param {string} type - The attribute's type.
  37211. * @return {NodeAttribute} The node attribute.
  37212. */
  37213. getAttribute( name, type ) {
  37214. const attributes = this.attributes;
  37215. // find attribute
  37216. for ( const attribute of attributes ) {
  37217. if ( attribute.name === name ) {
  37218. return attribute;
  37219. }
  37220. }
  37221. // create a new if no exist
  37222. const attribute = new NodeAttribute( name, type );
  37223. this.registerDeclaration( attribute );
  37224. attributes.push( attribute );
  37225. return attribute;
  37226. }
  37227. /**
  37228. * Returns for the given node and shader stage the property name for the shader.
  37229. *
  37230. * @param {Node} node - The node.
  37231. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37232. * @return {string} The property name.
  37233. */
  37234. getPropertyName( node/*, shaderStage*/ ) {
  37235. return node.name;
  37236. }
  37237. /**
  37238. * Whether the given type is a vector type or not.
  37239. *
  37240. * @param {string} type - The type to check.
  37241. * @return {boolean} Whether the given type is a vector type or not.
  37242. */
  37243. isVector( type ) {
  37244. return /vec\d/.test( type );
  37245. }
  37246. /**
  37247. * Whether the given type is a matrix type or not.
  37248. *
  37249. * @param {string} type - The type to check.
  37250. * @return {boolean} Whether the given type is a matrix type or not.
  37251. */
  37252. isMatrix( type ) {
  37253. return /mat\d/.test( type );
  37254. }
  37255. /**
  37256. * Whether the given type is a reference type or not.
  37257. *
  37258. * @param {string} type - The type to check.
  37259. * @return {boolean} Whether the given type is a reference type or not.
  37260. */
  37261. isReference( type ) {
  37262. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  37263. }
  37264. /**
  37265. * Checks if the given texture requires a manual conversion to the working color space.
  37266. *
  37267. * @abstract
  37268. * @param {Texture} texture - The texture to check.
  37269. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  37270. */
  37271. needsToWorkingColorSpace( /*texture*/ ) {
  37272. return false;
  37273. }
  37274. /**
  37275. * Returns the component type of a given texture.
  37276. *
  37277. * @param {Texture} texture - The texture.
  37278. * @return {string} The component type.
  37279. */
  37280. getComponentTypeFromTexture( texture ) {
  37281. const type = texture.type;
  37282. if ( texture.isDepthTexture === true ) return 'float';
  37283. if ( type === IntType ) return 'int';
  37284. if ( type === UnsignedIntType ) return 'uint';
  37285. return 'float';
  37286. }
  37287. /**
  37288. * Returns the element type for a given type.
  37289. *
  37290. * @param {string} type - The type.
  37291. * @return {string} The element type.
  37292. */
  37293. getElementType( type ) {
  37294. if ( type === 'mat2' ) return 'vec2';
  37295. if ( type === 'mat3' ) return 'vec3';
  37296. if ( type === 'mat4' ) return 'vec4';
  37297. return this.getComponentType( type );
  37298. }
  37299. /**
  37300. * Returns the component type for a given type.
  37301. *
  37302. * @param {string} type - The type.
  37303. * @return {string} The component type.
  37304. */
  37305. getComponentType( type ) {
  37306. type = this.getVectorType( type );
  37307. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  37308. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  37309. if ( componentType === null ) return null;
  37310. if ( componentType[ 1 ] === 'b' ) return 'bool';
  37311. if ( componentType[ 1 ] === 'i' ) return 'int';
  37312. if ( componentType[ 1 ] === 'u' ) return 'uint';
  37313. return 'float';
  37314. }
  37315. /**
  37316. * Returns the vector type for a given type.
  37317. *
  37318. * @param {string} type - The type.
  37319. * @return {string} The vector type.
  37320. */
  37321. getVectorType( type ) {
  37322. if ( type === 'color' ) return 'vec3';
  37323. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  37324. return type;
  37325. }
  37326. /**
  37327. * Returns the data type for the given the length and component type.
  37328. *
  37329. * @param {number} length - The length.
  37330. * @param {string} [componentType='float'] - The component type.
  37331. * @return {string} The type.
  37332. */
  37333. getTypeFromLength( length, componentType = 'float' ) {
  37334. if ( length === 1 ) return componentType;
  37335. let baseType = getTypeFromLength( length );
  37336. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  37337. // fix edge case for mat2x2 being same size as vec4
  37338. if ( /mat2/.test( componentType ) === true ) {
  37339. baseType = baseType.replace( 'vec', 'mat' );
  37340. }
  37341. return prefix + baseType;
  37342. }
  37343. /**
  37344. * Returns the type for a given typed array.
  37345. *
  37346. * @param {TypedArray} array - The typed array.
  37347. * @return {string} The type.
  37348. */
  37349. getTypeFromArray( array ) {
  37350. return typeFromArray.get( array.constructor );
  37351. }
  37352. /**
  37353. * Returns the type is an integer type.
  37354. *
  37355. * @param {string} type - The type.
  37356. * @return {boolean} Whether the type is an integer type or not.
  37357. */
  37358. isInteger( type ) {
  37359. return /int|uint|(i|u)vec/.test( type );
  37360. }
  37361. /**
  37362. * Returns the type for a given buffer attribute.
  37363. *
  37364. * @param {BufferAttribute} attribute - The buffer attribute.
  37365. * @return {string} The type.
  37366. */
  37367. getTypeFromAttribute( attribute ) {
  37368. let dataAttribute = attribute;
  37369. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  37370. const array = dataAttribute.array;
  37371. const itemSize = attribute.itemSize;
  37372. const normalized = attribute.normalized;
  37373. let arrayType;
  37374. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  37375. arrayType = this.getTypeFromArray( array );
  37376. }
  37377. return this.getTypeFromLength( itemSize, arrayType );
  37378. }
  37379. /**
  37380. * Returns the length for the given data type.
  37381. *
  37382. * @param {string} type - The data type.
  37383. * @return {number} The length.
  37384. */
  37385. getTypeLength( type ) {
  37386. const vecType = this.getVectorType( type );
  37387. const vecNum = /vec([2-4])/.exec( vecType );
  37388. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  37389. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  37390. if ( /mat2/.test( type ) === true ) return 4;
  37391. if ( /mat3/.test( type ) === true ) return 9;
  37392. if ( /mat4/.test( type ) === true ) return 16;
  37393. return 0;
  37394. }
  37395. /**
  37396. * Returns the vector type for a given matrix type.
  37397. *
  37398. * @param {string} type - The matrix type.
  37399. * @return {string} The vector type.
  37400. */
  37401. getVectorFromMatrix( type ) {
  37402. return type.replace( 'mat', 'vec' );
  37403. }
  37404. /**
  37405. * For a given type this method changes the component type to the
  37406. * given value. E.g. `vec4` should be changed to the new component type
  37407. * `uint` which results in `uvec4`.
  37408. *
  37409. * @param {string} type - The type.
  37410. * @param {string} newComponentType - The new component type.
  37411. * @return {string} The new type.
  37412. */
  37413. changeComponentType( type, newComponentType ) {
  37414. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  37415. }
  37416. /**
  37417. * Returns the integer type pendant for the given type.
  37418. *
  37419. * @param {string} type - The type.
  37420. * @return {string} The integer type.
  37421. */
  37422. getIntegerType( type ) {
  37423. const componentType = this.getComponentType( type );
  37424. if ( componentType === 'int' || componentType === 'uint' ) return type;
  37425. return this.changeComponentType( type, 'int' );
  37426. }
  37427. /**
  37428. * Adds an active stack to the internal stack.
  37429. *
  37430. * @param {StackNode} stack - The stack node to add.
  37431. */
  37432. setActiveStack( stack ) {
  37433. this.activeStacks.push( stack );
  37434. }
  37435. /**
  37436. * Removes the active stack from the internal stack.
  37437. *
  37438. * @param {StackNode} stack - The stack node to remove.
  37439. */
  37440. removeActiveStack( stack ) {
  37441. if ( this.activeStacks[ this.activeStacks.length - 1 ] === stack ) {
  37442. this.activeStacks.pop();
  37443. } else {
  37444. throw new Error( 'THREE.NodeBuilder: Invalid active stack removal.' );
  37445. }
  37446. }
  37447. /**
  37448. * Returns the active stack.
  37449. *
  37450. * @return {StackNode} The active stack.
  37451. */
  37452. getActiveStack() {
  37453. return this.activeStacks[ this.activeStacks.length - 1 ];
  37454. }
  37455. /**
  37456. * Returns the base stack.
  37457. *
  37458. * @return {StackNode} The base stack.
  37459. */
  37460. getBaseStack() {
  37461. return this.activeStacks[ 0 ];
  37462. }
  37463. /**
  37464. * Adds a stack node to the internal stack.
  37465. *
  37466. * @return {StackNode} The added stack node.
  37467. */
  37468. addStack() {
  37469. this.stack = stack( this.stack );
  37470. const previousStack = getCurrentStack();
  37471. this.stacks.push( previousStack );
  37472. setCurrentStack( this.stack );
  37473. return this.stack;
  37474. }
  37475. /**
  37476. * Removes the last stack node from the internal stack.
  37477. *
  37478. * @return {StackNode} The removed stack node.
  37479. */
  37480. removeStack() {
  37481. const lastStack = this.stack;
  37482. for ( const node of lastStack.nodes ) {
  37483. const nodeData = this.getDataFromNode( node );
  37484. nodeData.stack = lastStack;
  37485. }
  37486. this.stack = lastStack.parent;
  37487. setCurrentStack( this.stacks.pop() );
  37488. return lastStack;
  37489. }
  37490. /**
  37491. * The builder maintains (cached) data for each node during the building process. This method
  37492. * can be used to get these data for a specific shader stage and cache.
  37493. *
  37494. * @param {Node} node - The node to get the data for.
  37495. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  37496. * @param {?NodeCache} cache - An optional cache.
  37497. * @return {Object} The node data.
  37498. */
  37499. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  37500. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  37501. let nodeData = cache.getData( node );
  37502. if ( nodeData === undefined ) {
  37503. nodeData = {};
  37504. cache.setData( node, nodeData );
  37505. }
  37506. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  37507. //
  37508. let data = nodeData[ shaderStage ];
  37509. if ( this.subBuildLayers.length === 0 ) return data;
  37510. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  37511. const subBuild = this.getClosestSubBuild( subBuilds );
  37512. if ( subBuild ) {
  37513. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  37514. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  37515. data.subBuilds = subBuilds;
  37516. }
  37517. return data;
  37518. }
  37519. /**
  37520. * Returns the properties for the given node and shader stage.
  37521. *
  37522. * Properties are typically used within a build stage to reference a node's
  37523. * child node or nodes manually assigned to the properties in a separate build stage.
  37524. * A typical usage pattern for defining nodes manually would be assigning dependency nodes
  37525. * to the current node's properties in the setup stage and building those properties in the generate stage.
  37526. *
  37527. * @param {Node} node - The node to get the properties for.
  37528. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  37529. * @return {Object} The node properties.
  37530. */
  37531. getNodeProperties( node, shaderStage = 'any' ) {
  37532. const nodeData = this.getDataFromNode( node, shaderStage );
  37533. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  37534. }
  37535. /**
  37536. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  37537. *
  37538. * @param {BufferAttributeNode} node - The buffer attribute node.
  37539. * @param {string} type - The node type.
  37540. * @param {?string} [name=null] - The name of the buffer attribute.
  37541. * @return {NodeAttribute} The node attribute.
  37542. */
  37543. getBufferAttributeFromNode( node, type, name = null ) {
  37544. const nodeData = this.getDataFromNode( node, 'vertex' );
  37545. let bufferAttribute = nodeData.bufferAttribute;
  37546. if ( bufferAttribute === undefined ) {
  37547. const index = this.uniforms.index ++;
  37548. if ( name === null ) {
  37549. name = 'nodeAttribute' + index;
  37550. }
  37551. bufferAttribute = new NodeAttribute( name, type, node );
  37552. this.bufferAttributes.push( bufferAttribute );
  37553. nodeData.bufferAttribute = bufferAttribute;
  37554. }
  37555. return bufferAttribute;
  37556. }
  37557. /**
  37558. * Returns an instance of {@link StructType} for the given struct name and shader stage
  37559. * or null if not found.
  37560. *
  37561. * @param {string} name - The name of the struct.
  37562. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  37563. * @return {?StructType} The struct type or null if not found.
  37564. */
  37565. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  37566. return this.types[ shaderStage ][ name ] || null;
  37567. }
  37568. /**
  37569. * Returns an instance of {@link StructType} for the given output struct node.
  37570. *
  37571. * @param {OutputStructNode} node - The output struct node.
  37572. * @param {Array<Object>} membersLayout - The output struct types.
  37573. * @param {?string} [name=null] - The name of the struct.
  37574. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  37575. * @return {StructType} The struct type attribute.
  37576. */
  37577. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  37578. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  37579. let structType = nodeData.structType;
  37580. if ( structType === undefined ) {
  37581. const index = this.structs.index ++;
  37582. if ( name === null ) name = 'StructType' + index;
  37583. structType = new StructType( name, membersLayout );
  37584. this.structs[ shaderStage ].push( structType );
  37585. this.types[ shaderStage ][ name ] = node;
  37586. nodeData.structType = structType;
  37587. }
  37588. return structType;
  37589. }
  37590. /**
  37591. * Returns an instance of {@link StructType} for the given output struct node.
  37592. *
  37593. * @param {OutputStructNode} node - The output struct node.
  37594. * @param {Array<Object>} membersLayout - The output struct types.
  37595. * @return {StructType} The struct type attribute.
  37596. */
  37597. getOutputStructTypeFromNode( node, membersLayout ) {
  37598. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  37599. structType.output = true;
  37600. return structType;
  37601. }
  37602. /**
  37603. * Returns an instance of {@link NodeUniform} for the given uniform node.
  37604. *
  37605. * @param {UniformNode} node - The uniform node.
  37606. * @param {string} type - The uniform type.
  37607. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  37608. * @param {?string} name - The name of the uniform.
  37609. * @return {NodeUniform} The node uniform.
  37610. */
  37611. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  37612. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  37613. let nodeUniform = nodeData.uniform;
  37614. if ( nodeUniform === undefined ) {
  37615. const index = this.uniforms.index ++;
  37616. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  37617. this.uniforms[ shaderStage ].push( nodeUniform );
  37618. this.registerDeclaration( nodeUniform );
  37619. nodeData.uniform = nodeUniform;
  37620. }
  37621. return nodeUniform;
  37622. }
  37623. /**
  37624. * Returns an instance of {@link NodeVar} for the given variable node.
  37625. *
  37626. * @param {VarNode} node - The variable node.
  37627. * @param {?string} name - The variable's name.
  37628. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  37629. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  37630. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  37631. *
  37632. * @return {NodeVar} The node variable.
  37633. */
  37634. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  37635. const nodeData = this.getDataFromNode( node, shaderStage );
  37636. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  37637. let nodeVar = nodeData[ subBuildVariable ];
  37638. if ( nodeVar === undefined ) {
  37639. const idNS = readOnly ? '_const' : '_var';
  37640. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  37641. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  37642. if ( name === null ) {
  37643. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  37644. this.vars[ idNS ] ++;
  37645. }
  37646. //
  37647. if ( subBuildVariable !== 'variable' ) {
  37648. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  37649. }
  37650. //
  37651. const count = node.getArrayCount( this );
  37652. nodeVar = new NodeVar( name, type, readOnly, count );
  37653. if ( ! readOnly ) {
  37654. vars.push( nodeVar );
  37655. }
  37656. this.registerDeclaration( nodeVar );
  37657. nodeData[ subBuildVariable ] = nodeVar;
  37658. }
  37659. return nodeVar;
  37660. }
  37661. /**
  37662. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  37663. *
  37664. * @param {Node} node - The varying node.
  37665. * @return {boolean} Returns true if deterministic.
  37666. */
  37667. isDeterministic( node ) {
  37668. if ( node.isMathNode ) {
  37669. return this.isDeterministic( node.aNode ) &&
  37670. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  37671. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  37672. } else if ( node.isOperatorNode ) {
  37673. return this.isDeterministic( node.aNode ) &&
  37674. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  37675. } else if ( node.isArrayNode ) {
  37676. if ( node.values !== null ) {
  37677. for ( const n of node.values ) {
  37678. if ( ! this.isDeterministic( n ) ) {
  37679. return false;
  37680. }
  37681. }
  37682. }
  37683. return true;
  37684. } else if ( node.isConstNode ) {
  37685. return true;
  37686. }
  37687. return false;
  37688. }
  37689. /**
  37690. * Returns an instance of {@link NodeVarying} for the given varying node.
  37691. *
  37692. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  37693. * @param {?string} name - The varying's name.
  37694. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  37695. * @param {?string} interpolationType - The interpolation type of the varying.
  37696. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  37697. * @return {NodeVar} The node varying.
  37698. */
  37699. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  37700. const nodeData = this.getDataFromNode( node, 'any' );
  37701. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  37702. let nodeVarying = nodeData[ subBuildVarying ];
  37703. if ( nodeVarying === undefined ) {
  37704. const varyings = this.varyings;
  37705. const index = varyings.length;
  37706. if ( name === null ) name = 'nodeVarying' + index;
  37707. //
  37708. if ( subBuildVarying !== 'varying' ) {
  37709. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  37710. }
  37711. //
  37712. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  37713. varyings.push( nodeVarying );
  37714. this.registerDeclaration( nodeVarying );
  37715. nodeData[ subBuildVarying ] = nodeVarying;
  37716. }
  37717. return nodeVarying;
  37718. }
  37719. /**
  37720. * Registers a node declaration in the current shader stage.
  37721. *
  37722. * @param {Object} node - The node to be registered.
  37723. */
  37724. registerDeclaration( node ) {
  37725. const shaderStage = this.shaderStage;
  37726. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  37727. const property = this.getPropertyName( node );
  37728. let index = 1;
  37729. let name = property;
  37730. // Automatically renames the property if the name is already in use.
  37731. while ( declarations[ name ] !== undefined ) {
  37732. name = property + '_' + index ++;
  37733. }
  37734. if ( index > 1 ) {
  37735. node.name = name;
  37736. warn( `TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  37737. }
  37738. declarations[ name ] = node;
  37739. }
  37740. /**
  37741. * Returns an instance of {@link NodeCode} for the given code node.
  37742. *
  37743. * @param {CodeNode} node - The code node.
  37744. * @param {string} type - The node type.
  37745. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  37746. * @return {NodeCode} The node code.
  37747. */
  37748. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  37749. const nodeData = this.getDataFromNode( node );
  37750. let nodeCode = nodeData.code;
  37751. if ( nodeCode === undefined ) {
  37752. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  37753. const index = codes.length;
  37754. nodeCode = new NodeCode( 'nodeCode' + index, type );
  37755. codes.push( nodeCode );
  37756. nodeData.code = nodeCode;
  37757. }
  37758. return nodeCode;
  37759. }
  37760. /**
  37761. * Adds a code flow based on the code-block hierarchy.
  37762. * This is used so that code-blocks like If,Else create their variables locally if the Node
  37763. * is only used inside one of these conditionals in the current shader stage.
  37764. *
  37765. * @param {Node} node - The node to add.
  37766. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  37767. */
  37768. addFlowCodeHierarchy( node, nodeBlock ) {
  37769. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  37770. let needsFlowCode = true;
  37771. let nodeBlockHierarchy = nodeBlock;
  37772. while ( nodeBlockHierarchy ) {
  37773. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  37774. needsFlowCode = false;
  37775. break;
  37776. }
  37777. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  37778. }
  37779. if ( needsFlowCode ) {
  37780. for ( const flowCode of flowCodes ) {
  37781. this.addLineFlowCode( flowCode );
  37782. }
  37783. }
  37784. }
  37785. /**
  37786. * Add a inline-code to the current flow code-block.
  37787. *
  37788. * @param {Node} node - The node to add.
  37789. * @param {string} code - The code to add.
  37790. * @param {Node} nodeBlock - Current ConditionalNode
  37791. */
  37792. addLineFlowCodeBlock( node, code, nodeBlock ) {
  37793. const nodeData = this.getDataFromNode( node );
  37794. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  37795. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  37796. flowCodes.push( code );
  37797. codeBlock.set( nodeBlock, true );
  37798. }
  37799. /**
  37800. * Add a inline-code to the current flow.
  37801. *
  37802. * @param {string} code - The code to add.
  37803. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  37804. * @return {NodeBuilder} A reference to this node builder.
  37805. */
  37806. addLineFlowCode( code, node = null ) {
  37807. if ( code === '' ) return this;
  37808. if ( node !== null && this.context.nodeBlock ) {
  37809. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  37810. }
  37811. code = this.tab + code;
  37812. if ( ! /;\s*$/.test( code ) ) {
  37813. code = code + ';\n';
  37814. }
  37815. this.flow.code += code;
  37816. return this;
  37817. }
  37818. /**
  37819. * Adds a code to the current code flow.
  37820. *
  37821. * @param {string} code - Shader code.
  37822. * @return {NodeBuilder} A reference to this node builder.
  37823. */
  37824. addFlowCode( code ) {
  37825. this.flow.code += code;
  37826. return this;
  37827. }
  37828. /**
  37829. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  37830. * Typically used in codes with If,Else.
  37831. *
  37832. * @return {NodeBuilder} A reference to this node builder.
  37833. */
  37834. addFlowTab() {
  37835. this.tab += '\t';
  37836. return this;
  37837. }
  37838. /**
  37839. * Removes a tab.
  37840. *
  37841. * @return {NodeBuilder} A reference to this node builder.
  37842. */
  37843. removeFlowTab() {
  37844. this.tab = this.tab.slice( 0, -1 );
  37845. return this;
  37846. }
  37847. /**
  37848. * Gets the current flow data based on a Node.
  37849. *
  37850. * @param {Node} node - Node that the flow was started.
  37851. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37852. * @return {Object} The flow data.
  37853. */
  37854. getFlowData( node/*, shaderStage*/ ) {
  37855. return this.flowsData.get( node );
  37856. }
  37857. /**
  37858. * Executes the node flow based on a root node to generate the final shader code.
  37859. *
  37860. * @param {Node} node - The node to execute.
  37861. * @return {Object} The code flow.
  37862. */
  37863. flowNode( node ) {
  37864. const output = node.getNodeType( this );
  37865. const flowData = this.flowChildNode( node, output );
  37866. this.flowsData.set( node, flowData );
  37867. return flowData;
  37868. }
  37869. /**
  37870. * Includes a node in the current function node.
  37871. *
  37872. * @param {Node} node - The node to include.
  37873. * @returns {void}
  37874. */
  37875. addInclude( node ) {
  37876. if ( this.currentFunctionNode !== null ) {
  37877. this.currentFunctionNode.includes.push( node );
  37878. }
  37879. }
  37880. /**
  37881. * Returns the native shader operator name for a given generic name.
  37882. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  37883. *
  37884. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  37885. * @return {FunctionNode} The build function node.
  37886. */
  37887. buildFunctionNode( shaderNode ) {
  37888. const backend = this.renderer.backend;
  37889. let cache = _functionNodeCache.get( backend );
  37890. if ( cache === undefined ) {
  37891. cache = new WeakMap();
  37892. _functionNodeCache.set( backend, cache );
  37893. }
  37894. let fn = cache.get( shaderNode );
  37895. if ( fn === undefined ) {
  37896. fn = new FunctionNode();
  37897. const previous = this.currentFunctionNode;
  37898. this.currentFunctionNode = fn;
  37899. fn.code = this.buildFunctionCode( shaderNode );
  37900. this.currentFunctionNode = previous;
  37901. cache.set( shaderNode, fn );
  37902. }
  37903. return fn;
  37904. }
  37905. /**
  37906. * Generates a code flow based on a TSL function: Fn().
  37907. *
  37908. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  37909. * @return {Object}
  37910. */
  37911. flowShaderNode( shaderNode ) {
  37912. const layout = shaderNode.layout;
  37913. const inputs = {
  37914. [ Symbol.iterator ]() {
  37915. let index = 0;
  37916. const values = Object.values( this );
  37917. return {
  37918. next: () => ( {
  37919. value: values[ index ],
  37920. done: index ++ >= values.length
  37921. } )
  37922. };
  37923. }
  37924. };
  37925. for ( const input of layout.inputs ) {
  37926. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  37927. }
  37928. //
  37929. shaderNode.layout = null;
  37930. const callNode = shaderNode.call( inputs );
  37931. const flowData = this.flowStagesNode( callNode, layout.type );
  37932. shaderNode.layout = layout;
  37933. return flowData;
  37934. }
  37935. /**
  37936. * Executes the node in a specific build stage.
  37937. *
  37938. * This function can be used to arbitrarily execute the specified build stage
  37939. * outside of the standard build process. For instance, if a node's type depends
  37940. * on properties created by the 'setup' stage, then flowBuildStage(node, 'setup')
  37941. * can be used to execute the setup build stage and access its generated nodes
  37942. * before the standard build process begins.
  37943. *
  37944. * @param {Node} node - The node to execute.
  37945. * @param {string} buildStage - The build stage to execute the node in.
  37946. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  37947. * @return {?(Node|string)} The result of the node build.
  37948. */
  37949. flowBuildStage( node, buildStage, output = null ) {
  37950. const previousBuildStage = this.getBuildStage();
  37951. this.setBuildStage( buildStage );
  37952. const result = node.build( this, output );
  37953. this.setBuildStage( previousBuildStage );
  37954. return result;
  37955. }
  37956. /**
  37957. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  37958. *
  37959. * @param {Node} node - The node to execute.
  37960. * @param {?string} output - Expected output type. For example 'vec3'.
  37961. * @return {Object}
  37962. */
  37963. flowStagesNode( node, output = null ) {
  37964. const previousFlow = this.flow;
  37965. const previousVars = this.vars;
  37966. const previousDeclarations = this.declarations;
  37967. const previousCache = this.cache;
  37968. const previousBuildStage = this.buildStage;
  37969. const previousStack = this.stack;
  37970. const flow = {
  37971. code: ''
  37972. };
  37973. this.flow = flow;
  37974. this.vars = {};
  37975. this.declarations = {};
  37976. this.cache = new NodeCache();
  37977. this.stack = stack();
  37978. for ( const buildStage of defaultBuildStages ) {
  37979. this.setBuildStage( buildStage );
  37980. flow.result = node.build( this, output );
  37981. }
  37982. flow.vars = this.getVars( this.shaderStage );
  37983. this.flow = previousFlow;
  37984. this.vars = previousVars;
  37985. this.declarations = previousDeclarations;
  37986. this.cache = previousCache;
  37987. this.stack = previousStack;
  37988. this.setBuildStage( previousBuildStage );
  37989. return flow;
  37990. }
  37991. /**
  37992. * Returns the native shader operator name for a given generic name.
  37993. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  37994. *
  37995. * @abstract
  37996. * @param {string} op - The operator name to resolve.
  37997. * @return {?string} The resolved operator name.
  37998. */
  37999. getFunctionOperator( /* op */ ) {
  38000. return null;
  38001. }
  38002. /**
  38003. * Builds the given shader node.
  38004. *
  38005. * @abstract
  38006. * @param {ShaderNodeInternal} shaderNode - The shader node.
  38007. * @return {string} The function code.
  38008. */
  38009. buildFunctionCode( /* shaderNode */ ) {
  38010. warn( 'Abstract function.' );
  38011. }
  38012. /**
  38013. * Generates a code flow based on a child Node.
  38014. *
  38015. * @param {Node} node - The node to execute.
  38016. * @param {?string} output - Expected output type. For example 'vec3'.
  38017. * @return {Object} The code flow.
  38018. */
  38019. flowChildNode( node, output = null ) {
  38020. const previousFlow = this.flow;
  38021. const flow = {
  38022. code: ''
  38023. };
  38024. this.flow = flow;
  38025. flow.result = node.build( this, output );
  38026. this.flow = previousFlow;
  38027. return flow;
  38028. }
  38029. /**
  38030. * Executes a flow of code in a different stage.
  38031. *
  38032. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  38033. * return the value in fragment-stage even if it is being executed in an input fragment.
  38034. *
  38035. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  38036. * @param {Node} node - The node to execute.
  38037. * @param {?string} output - Expected output type. For example 'vec3'.
  38038. * @param {?string} propertyName - The property name to assign the result.
  38039. * @return {?(Object|Node)} The code flow or node.build() result.
  38040. */
  38041. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  38042. const previousTab = this.tab;
  38043. const previousCache = this.cache;
  38044. const previousShaderStage = this.shaderStage;
  38045. const previousContext = this.context;
  38046. this.setShaderStage( shaderStage );
  38047. const context = { ...this.context };
  38048. delete context.nodeBlock;
  38049. this.cache = this.globalCache;
  38050. this.tab = '\t';
  38051. this.context = context;
  38052. let result = null;
  38053. if ( this.buildStage === 'generate' ) {
  38054. const flowData = this.flowChildNode( node, output );
  38055. if ( propertyName !== null ) {
  38056. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  38057. }
  38058. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  38059. result = flowData;
  38060. } else {
  38061. result = node.build( this );
  38062. }
  38063. this.setShaderStage( previousShaderStage );
  38064. this.cache = previousCache;
  38065. this.tab = previousTab;
  38066. this.context = previousContext;
  38067. return result;
  38068. }
  38069. /**
  38070. * Returns an array holding all node attributes of this node builder.
  38071. *
  38072. * @return {Array<NodeAttribute>} The node attributes of this builder.
  38073. */
  38074. getAttributesArray() {
  38075. return this.attributes.concat( this.bufferAttributes );
  38076. }
  38077. /**
  38078. * Returns the attribute definitions as a shader string for the given shader stage.
  38079. *
  38080. * @abstract
  38081. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  38082. * @return {string} The attribute code section.
  38083. */
  38084. getAttributes( /*shaderStage*/ ) {
  38085. warn( 'Abstract function.' );
  38086. }
  38087. /**
  38088. * Returns the varying definitions as a shader string for the given shader stage.
  38089. *
  38090. * @abstract
  38091. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  38092. * @return {string} The varying code section.
  38093. */
  38094. getVaryings( /*shaderStage*/ ) {
  38095. warn( 'Abstract function.' );
  38096. }
  38097. /**
  38098. * Returns a single variable definition as a shader string for the given variable type and name.
  38099. *
  38100. * @param {string} type - The variable's type.
  38101. * @param {string} name - The variable's name.
  38102. * @param {?number} [count=null] - The array length.
  38103. * @return {string} The shader string.
  38104. */
  38105. getVar( type, name, count = null ) {
  38106. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  38107. }
  38108. /**
  38109. * Returns the variable definitions as a shader string for the given shader stage.
  38110. *
  38111. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  38112. * @param {boolean} [global=false] - Whether the variables are global.
  38113. * @return {string} The variable code section.
  38114. */
  38115. getVars( shaderStage, global = false ) {
  38116. const snippets = [];
  38117. const vars = this.vars[ shaderStage ];
  38118. if ( vars !== undefined ) {
  38119. for ( const variable of vars ) {
  38120. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  38121. }
  38122. }
  38123. return snippets.join( global ? '\n' : '\n\t' );
  38124. }
  38125. /**
  38126. * Returns the uniform definitions as a shader string for the given shader stage.
  38127. *
  38128. * @abstract
  38129. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  38130. * @return {string} The uniform code section.
  38131. */
  38132. getUniforms( /*shaderStage*/ ) {
  38133. warn( 'Abstract function.' );
  38134. }
  38135. /**
  38136. * Returns the native code definitions as a shader string for the given shader stage.
  38137. *
  38138. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  38139. * @return {string} The native code section.
  38140. */
  38141. getCodes( shaderStage ) {
  38142. const codes = this.codes[ shaderStage ];
  38143. let code = '';
  38144. if ( codes !== undefined ) {
  38145. for ( const nodeCode of codes ) {
  38146. code += nodeCode.code + '\n';
  38147. }
  38148. }
  38149. return code;
  38150. }
  38151. /**
  38152. * Returns the hash of this node builder.
  38153. *
  38154. * @return {string} The hash.
  38155. */
  38156. getHash() {
  38157. return this.vertexShader + this.fragmentShader + this.computeShader;
  38158. }
  38159. /**
  38160. * Sets the current shader stage.
  38161. *
  38162. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  38163. */
  38164. setShaderStage( shaderStage ) {
  38165. this.shaderStage = shaderStage;
  38166. }
  38167. /**
  38168. * Returns the current shader stage.
  38169. *
  38170. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  38171. */
  38172. getShaderStage() {
  38173. return this.shaderStage;
  38174. }
  38175. /**
  38176. * Sets the current build stage.
  38177. *
  38178. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  38179. */
  38180. setBuildStage( buildStage ) {
  38181. this.buildStage = buildStage;
  38182. }
  38183. /**
  38184. * Returns the current build stage.
  38185. *
  38186. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  38187. */
  38188. getBuildStage() {
  38189. return this.buildStage;
  38190. }
  38191. /**
  38192. * Controls the code build of the shader stages.
  38193. *
  38194. * @abstract
  38195. */
  38196. buildCode() {
  38197. warn( 'Abstract function.' );
  38198. }
  38199. /**
  38200. * Returns the current sub-build layer.
  38201. *
  38202. * @return {SubBuildNode} The current sub-build layers.
  38203. */
  38204. get subBuild() {
  38205. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  38206. }
  38207. /**
  38208. * Adds a sub-build layer to the node builder.
  38209. *
  38210. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  38211. */
  38212. addSubBuild( subBuild ) {
  38213. this.subBuildLayers.push( subBuild );
  38214. }
  38215. /**
  38216. * Removes the last sub-build layer from the node builder.
  38217. *
  38218. * @return {SubBuildNode} The removed sub-build layer.
  38219. */
  38220. removeSubBuild() {
  38221. return this.subBuildLayers.pop();
  38222. }
  38223. /**
  38224. * Returns the closest sub-build layer for the given data.
  38225. *
  38226. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  38227. * @return {?string} The closest sub-build name or null if none found.
  38228. */
  38229. getClosestSubBuild( data ) {
  38230. let subBuilds;
  38231. if ( data && data.isNode ) {
  38232. if ( data.isShaderCallNodeInternal ) {
  38233. subBuilds = data.shaderNode.subBuilds;
  38234. } else if ( data.isStackNode ) {
  38235. subBuilds = [ data.subBuild ];
  38236. } else {
  38237. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  38238. }
  38239. } else if ( data instanceof Set ) {
  38240. subBuilds = [ ...data ];
  38241. } else {
  38242. subBuilds = data;
  38243. }
  38244. if ( ! subBuilds ) return null;
  38245. const subBuildLayers = this.subBuildLayers;
  38246. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  38247. const subBuild = subBuilds[ i ];
  38248. if ( subBuildLayers.includes( subBuild ) ) {
  38249. return subBuild;
  38250. }
  38251. }
  38252. return null;
  38253. }
  38254. /**
  38255. * Returns the output node of a sub-build layer.
  38256. *
  38257. * @param {Node} node - The node to get the output from.
  38258. * @return {string} The output node name.
  38259. */
  38260. getSubBuildOutput( node ) {
  38261. return this.getSubBuildProperty( 'outputNode', node );
  38262. }
  38263. /**
  38264. * Returns the sub-build property name for the given property and node.
  38265. *
  38266. * @param {string} [property=''] - The property name.
  38267. * @param {?Node} [node=null] - The node to get the sub-build from.
  38268. * @return {string} The sub-build property name.
  38269. */
  38270. getSubBuildProperty( property = '', node = null ) {
  38271. let subBuild;
  38272. if ( node !== null ) {
  38273. subBuild = this.getClosestSubBuild( node );
  38274. } else {
  38275. subBuild = this.subBuildFn;
  38276. }
  38277. let result;
  38278. if ( subBuild ) {
  38279. result = property ? ( subBuild + '_' + property ) : subBuild;
  38280. } else {
  38281. result = property;
  38282. }
  38283. return result;
  38284. }
  38285. /**
  38286. * Prebuild the node builder.
  38287. */
  38288. prebuild() {
  38289. const { object, renderer, material } = this;
  38290. // < renderer.contextNode >
  38291. if ( renderer.contextNode.isContextNode === true ) {
  38292. this.context = { ...this.context, ...renderer.contextNode.getFlowContextData() };
  38293. } else {
  38294. error( 'NodeBuilder: "renderer.contextNode" must be an instance of `context()`.' );
  38295. }
  38296. // < material.contextNode >
  38297. if ( material && material.contextNode ) {
  38298. if ( material.contextNode.isContextNode === true ) {
  38299. this.context = { ...this.context, ...material.contextNode.getFlowContextData() };
  38300. } else {
  38301. error( 'NodeBuilder: "material.contextNode" must be an instance of `context()`.' );
  38302. }
  38303. }
  38304. // < nodeMaterial >
  38305. if ( material !== null ) {
  38306. let nodeMaterial = renderer.library.fromMaterial( material );
  38307. if ( nodeMaterial === null ) {
  38308. error( `NodeBuilder: Material "${ material.type }" is not compatible.` );
  38309. nodeMaterial = new NodeMaterial();
  38310. }
  38311. nodeMaterial.build( this );
  38312. } else {
  38313. this.addFlow( 'compute', object );
  38314. }
  38315. }
  38316. /**
  38317. * Central build method which controls the build for the given object.
  38318. *
  38319. * @return {NodeBuilder} A reference to this node builder.
  38320. */
  38321. build() {
  38322. this.prebuild();
  38323. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  38324. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  38325. // generate() -> stage 3: generate shader
  38326. for ( const buildStage of defaultBuildStages ) {
  38327. this.setBuildStage( buildStage );
  38328. if ( this.context.position && this.context.position.isNode ) {
  38329. this.flowNodeFromShaderStage( 'vertex', this.context.position );
  38330. }
  38331. for ( const shaderStage of shaderStages ) {
  38332. this.setShaderStage( shaderStage );
  38333. const flowNodes = this.flowNodes[ shaderStage ];
  38334. for ( const node of flowNodes ) {
  38335. if ( buildStage === 'generate' ) {
  38336. this.flowNode( node );
  38337. } else {
  38338. node.build( this );
  38339. }
  38340. }
  38341. }
  38342. }
  38343. this.setBuildStage( null );
  38344. this.setShaderStage( null );
  38345. // stage 4: build code for a specific output
  38346. this.buildCode();
  38347. this.buildUpdateNodes();
  38348. return this;
  38349. }
  38350. /**
  38351. * Async version of build() that yields to main thread between shader stages.
  38352. * Use this in compileAsync() to prevent blocking the main thread.
  38353. *
  38354. * @return {Promise<NodeBuilder>} A promise that resolves to this node builder.
  38355. */
  38356. async buildAsync() {
  38357. this.prebuild();
  38358. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  38359. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  38360. // generate() -> stage 3: generate shader
  38361. for ( const buildStage of defaultBuildStages ) {
  38362. this.setBuildStage( buildStage );
  38363. if ( this.context.position && this.context.position.isNode ) {
  38364. this.flowNodeFromShaderStage( 'vertex', this.context.position );
  38365. }
  38366. for ( const shaderStage of shaderStages ) {
  38367. this.setShaderStage( shaderStage );
  38368. const flowNodes = this.flowNodes[ shaderStage ];
  38369. for ( const node of flowNodes ) {
  38370. if ( buildStage === 'generate' ) {
  38371. this.flowNode( node );
  38372. } else {
  38373. node.build( this );
  38374. }
  38375. }
  38376. // Yield to main thread after each shader stage to prevent blocking
  38377. await yieldToMain();
  38378. }
  38379. }
  38380. this.setBuildStage( null );
  38381. this.setShaderStage( null );
  38382. // stage 4: build code for a specific output
  38383. this.buildCode();
  38384. this.buildUpdateNodes();
  38385. return this;
  38386. }
  38387. /**
  38388. * Returns shared data object for the given node.
  38389. *
  38390. * @param {Node} node - The node to get shared data from.
  38391. * @return {Object} The shared data.
  38392. */
  38393. getSharedDataFromNode( node ) {
  38394. let data = sharedNodeData.get( node );
  38395. if ( data === undefined ) {
  38396. data = {};
  38397. }
  38398. return data;
  38399. }
  38400. /**
  38401. * Returns a uniform representation which is later used for UBO generation and rendering.
  38402. *
  38403. * @param {NodeUniform} uniformNode - The uniform node.
  38404. * @param {string} type - The requested type.
  38405. * @return {Uniform} The uniform.
  38406. */
  38407. getNodeUniform( uniformNode, type ) {
  38408. const nodeData = this.getSharedDataFromNode( uniformNode );
  38409. let node = nodeData.cache;
  38410. if ( node === undefined ) {
  38411. if ( type === 'float' || type === 'int' || type === 'uint' ) node = new NumberNodeUniform( uniformNode );
  38412. else if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) node = new Vector2NodeUniform( uniformNode );
  38413. else if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) node = new Vector3NodeUniform( uniformNode );
  38414. else if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) node = new Vector4NodeUniform( uniformNode );
  38415. else if ( type === 'color' ) node = new ColorNodeUniform( uniformNode );
  38416. else if ( type === 'mat2' ) node = new Matrix2NodeUniform( uniformNode );
  38417. else if ( type === 'mat3' ) node = new Matrix3NodeUniform( uniformNode );
  38418. else if ( type === 'mat4' ) node = new Matrix4NodeUniform( uniformNode );
  38419. else {
  38420. throw new Error( `THREE.NodeBuilder: Uniform "${ type }" not implemented.` );
  38421. }
  38422. nodeData.cache = node;
  38423. }
  38424. return node;
  38425. }
  38426. /**
  38427. * Formats the given shader snippet from a given type into another one. E.g.
  38428. * this method might be used to convert a simple float string `"1.0"` into a
  38429. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  38430. *
  38431. * @param {string} snippet - The shader snippet.
  38432. * @param {string} fromType - The source type.
  38433. * @param {string} toType - The target type.
  38434. * @return {string} The updated shader string.
  38435. */
  38436. format( snippet, fromType, toType ) {
  38437. fromType = this.getVectorType( fromType );
  38438. toType = this.getVectorType( toType );
  38439. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  38440. return snippet;
  38441. }
  38442. const fromTypeLength = this.getTypeLength( fromType );
  38443. const toTypeLength = this.getTypeLength( toType );
  38444. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  38445. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  38446. }
  38447. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  38448. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  38449. }
  38450. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  38451. // @TODO: ignore for now
  38452. return snippet;
  38453. }
  38454. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  38455. // @TODO: ignore for now
  38456. return snippet;
  38457. }
  38458. if ( fromTypeLength === toTypeLength ) {
  38459. return `${ this.getType( toType ) }( ${ snippet } )`;
  38460. }
  38461. if ( fromTypeLength > toTypeLength ) {
  38462. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  38463. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  38464. }
  38465. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  38466. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  38467. }
  38468. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  38469. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  38470. }
  38471. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  38472. // convert a number value to vector type, e.g:
  38473. // vec3( 1u ) -> vec3( float( 1u ) )
  38474. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  38475. }
  38476. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  38477. }
  38478. /**
  38479. * Returns a signature with the engine's current revision.
  38480. *
  38481. * @return {string} The signature.
  38482. */
  38483. getSignature() {
  38484. return `// Three.js r${ REVISION } - Node System\n`;
  38485. }
  38486. /**
  38487. * Returns `true` if data from the previous frame are required. Relevant
  38488. * when computing motion vectors with {@link VelocityNode}.
  38489. *
  38490. * @return {boolean} Whether data from the previous frame are required or not.
  38491. */
  38492. needsPreviousData() {
  38493. const mrt = this.renderer.getMRT();
  38494. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( this.object ).useVelocity === true;
  38495. }
  38496. }
  38497. /**
  38498. * Management class for updating nodes. The module tracks metrics like
  38499. * the elapsed time, delta time, the render and frame ID to correctly
  38500. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  38501. * and {@link Node#updateAfter} depending on the node's configuration.
  38502. */
  38503. class NodeFrame {
  38504. /**
  38505. * Constructs a new node fame.
  38506. */
  38507. constructor() {
  38508. /**
  38509. * The elapsed time in seconds.
  38510. *
  38511. * @type {number}
  38512. * @default 0
  38513. */
  38514. this.time = 0;
  38515. /**
  38516. * The delta time in seconds.
  38517. *
  38518. * @type {number}
  38519. * @default 0
  38520. */
  38521. this.deltaTime = 0;
  38522. /**
  38523. * The frame ID.
  38524. *
  38525. * @type {number}
  38526. * @default 0
  38527. */
  38528. this.frameId = 0;
  38529. /**
  38530. * The render ID.
  38531. *
  38532. * @type {number}
  38533. * @default 0
  38534. */
  38535. this.renderId = 0;
  38536. /**
  38537. * Used to control the {@link Node#update} call.
  38538. *
  38539. * @type {WeakMap<Node, Object>}
  38540. */
  38541. this.updateMap = new WeakMap();
  38542. /**
  38543. * Used to control the {@link Node#updateBefore} call.
  38544. *
  38545. * @type {WeakMap<Node, Object>}
  38546. */
  38547. this.updateBeforeMap = new WeakMap();
  38548. /**
  38549. * Used to control the {@link Node#updateAfter} call.
  38550. *
  38551. * @type {WeakMap<Node, Object>}
  38552. */
  38553. this.updateAfterMap = new WeakMap();
  38554. /**
  38555. * A reference to the current renderer.
  38556. *
  38557. * @type {?Renderer}
  38558. * @default null
  38559. */
  38560. this.renderer = null;
  38561. /**
  38562. * A reference to the current material.
  38563. *
  38564. * @type {?Material}
  38565. * @default null
  38566. */
  38567. this.material = null;
  38568. /**
  38569. * A reference to the current camera.
  38570. *
  38571. * @type {?Camera}
  38572. * @default null
  38573. */
  38574. this.camera = null;
  38575. /**
  38576. * A reference to the current 3D object.
  38577. *
  38578. * @type {?Object3D}
  38579. * @default null
  38580. */
  38581. this.object = null;
  38582. /**
  38583. * A reference to the current scene.
  38584. *
  38585. * @type {?Scene}
  38586. * @default null
  38587. */
  38588. this.scene = null;
  38589. }
  38590. /**
  38591. * Returns a dictionary for a given node and update map which
  38592. * is used to correctly call node update methods per frame or render.
  38593. *
  38594. * @private
  38595. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  38596. * @param {Node} nodeRef - The reference to the current node.
  38597. * @return {Object<string,WeakMap<Object, number>>} The dictionary.
  38598. */
  38599. _getMaps( referenceMap, nodeRef ) {
  38600. let maps = referenceMap.get( nodeRef );
  38601. if ( maps === undefined ) {
  38602. maps = {
  38603. renderId: 0,
  38604. frameId: 0,
  38605. };
  38606. referenceMap.set( nodeRef, maps );
  38607. }
  38608. return maps;
  38609. }
  38610. /**
  38611. * This method executes the {@link Node#updateBefore} for the given node.
  38612. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  38613. * is only executed once per frame, render or object depending on the update
  38614. * type.
  38615. *
  38616. * @param {Node} node - The node that should be updated.
  38617. */
  38618. updateBeforeNode( node ) {
  38619. const updateType = node.getUpdateBeforeType();
  38620. const reference = node.updateReference( this );
  38621. if ( updateType === NodeUpdateType.FRAME ) {
  38622. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  38623. if ( nodeUpdateBeforeMap.frameId !== this.frameId ) {
  38624. const previousFrameId = nodeUpdateBeforeMap.frameId;
  38625. nodeUpdateBeforeMap.frameId = this.frameId;
  38626. if ( node.updateBefore( this ) === false ) {
  38627. nodeUpdateBeforeMap.frameId = previousFrameId;
  38628. }
  38629. }
  38630. } else if ( updateType === NodeUpdateType.RENDER ) {
  38631. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  38632. if ( nodeUpdateBeforeMap.renderId !== this.renderId ) {
  38633. const previousRenderId = nodeUpdateBeforeMap.renderId;
  38634. nodeUpdateBeforeMap.renderId = this.renderId;
  38635. if ( node.updateBefore( this ) === false ) {
  38636. nodeUpdateBeforeMap.renderId = previousRenderId;
  38637. }
  38638. }
  38639. } else if ( updateType === NodeUpdateType.OBJECT ) {
  38640. node.updateBefore( this );
  38641. }
  38642. }
  38643. /**
  38644. * This method executes the {@link Node#updateAfter} for the given node.
  38645. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  38646. * is only executed once per frame, render or object depending on the update
  38647. * type.
  38648. *
  38649. * @param {Node} node - The node that should be updated.
  38650. */
  38651. updateAfterNode( node ) {
  38652. const updateType = node.getUpdateAfterType();
  38653. const reference = node.updateReference( this );
  38654. if ( updateType === NodeUpdateType.FRAME ) {
  38655. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  38656. if ( nodeUpdateAfterMap.frameId !== this.frameId ) {
  38657. if ( node.updateAfter( this ) !== false ) {
  38658. nodeUpdateAfterMap.frameId = this.frameId;
  38659. }
  38660. }
  38661. } else if ( updateType === NodeUpdateType.RENDER ) {
  38662. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  38663. if ( nodeUpdateAfterMap.renderId !== this.renderId ) {
  38664. if ( node.updateAfter( this ) !== false ) {
  38665. nodeUpdateAfterMap.renderId = this.renderId;
  38666. }
  38667. }
  38668. } else if ( updateType === NodeUpdateType.OBJECT ) {
  38669. node.updateAfter( this );
  38670. }
  38671. }
  38672. /**
  38673. * This method executes the {@link Node#update} for the given node.
  38674. * It makes sure {@link Node#updateType} is honored meaning the update
  38675. * is only executed once per frame, render or object depending on the update
  38676. * type.
  38677. *
  38678. * @param {Node} node - The node that should be updated.
  38679. */
  38680. updateNode( node ) {
  38681. const updateType = node.getUpdateType();
  38682. const reference = node.updateReference( this );
  38683. if ( updateType === NodeUpdateType.FRAME ) {
  38684. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  38685. if ( nodeUpdateMap.frameId !== this.frameId ) {
  38686. if ( node.update( this ) !== false ) {
  38687. nodeUpdateMap.frameId = this.frameId;
  38688. }
  38689. }
  38690. } else if ( updateType === NodeUpdateType.RENDER ) {
  38691. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  38692. if ( nodeUpdateMap.renderId !== this.renderId ) {
  38693. if ( node.update( this ) !== false ) {
  38694. nodeUpdateMap.renderId = this.renderId;
  38695. }
  38696. }
  38697. } else if ( updateType === NodeUpdateType.OBJECT ) {
  38698. node.update( this );
  38699. }
  38700. }
  38701. /**
  38702. * Updates the internal state of the node frame. This method is
  38703. * called by the renderer in its internal animation loop.
  38704. */
  38705. update() {
  38706. this.frameId ++;
  38707. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  38708. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  38709. this.lastTime = performance.now();
  38710. this.time += this.deltaTime;
  38711. }
  38712. }
  38713. /**
  38714. * Describes the input of a {@link NodeFunction}.
  38715. */
  38716. class NodeFunctionInput {
  38717. /**
  38718. * Constructs a new node function input.
  38719. *
  38720. * @param {string} type - The input type.
  38721. * @param {string} name - The input name.
  38722. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  38723. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  38724. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  38725. */
  38726. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  38727. /**
  38728. * The input type.
  38729. *
  38730. * @type {string}
  38731. */
  38732. this.type = type;
  38733. /**
  38734. * The input name.
  38735. *
  38736. * @type {string}
  38737. */
  38738. this.name = name;
  38739. /**
  38740. * If the input is an Array, count will be the length.
  38741. *
  38742. * @type {?number}
  38743. * @default null
  38744. */
  38745. this.count = count;
  38746. /**
  38747. *The parameter qualifier (only relevant for GLSL).
  38748. *
  38749. * @type {('in'|'out'|'inout')}
  38750. * @default ''
  38751. */
  38752. this.qualifier = qualifier;
  38753. /**
  38754. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  38755. *
  38756. * @type {boolean}
  38757. * @default false
  38758. */
  38759. this.isConst = isConst;
  38760. }
  38761. }
  38762. NodeFunctionInput.isNodeFunctionInput = true;
  38763. /**
  38764. * Module for representing ambient lights as nodes.
  38765. *
  38766. * @augments AnalyticLightNode
  38767. */
  38768. class AmbientLightNode extends AnalyticLightNode {
  38769. static get type() {
  38770. return 'AmbientLightNode';
  38771. }
  38772. /**
  38773. * Constructs a new ambient light node.
  38774. *
  38775. * @param {?AmbientLight} [light=null] - The ambient light source.
  38776. */
  38777. constructor( light = null ) {
  38778. super( light );
  38779. }
  38780. setup( { context } ) {
  38781. context.irradiance.addAssign( this.colorNode );
  38782. }
  38783. }
  38784. /**
  38785. * Module for representing directional lights as nodes.
  38786. *
  38787. * @augments AnalyticLightNode
  38788. */
  38789. class DirectionalLightNode extends AnalyticLightNode {
  38790. static get type() {
  38791. return 'DirectionalLightNode';
  38792. }
  38793. /**
  38794. * Constructs a new directional light node.
  38795. *
  38796. * @param {?DirectionalLight} [light=null] - The directional light source.
  38797. */
  38798. constructor( light = null ) {
  38799. super( light );
  38800. }
  38801. setupDirect() {
  38802. const lightColor = this.colorNode;
  38803. const lightDirection = lightTargetDirection( this.light );
  38804. return { lightDirection, lightColor };
  38805. }
  38806. }
  38807. /**
  38808. * Module for representing hemisphere lights as nodes.
  38809. *
  38810. * @augments AnalyticLightNode
  38811. */
  38812. class HemisphereLightNode extends AnalyticLightNode {
  38813. static get type() {
  38814. return 'HemisphereLightNode';
  38815. }
  38816. /**
  38817. * Constructs a new hemisphere light node.
  38818. *
  38819. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  38820. */
  38821. constructor( light = null ) {
  38822. super( light );
  38823. /**
  38824. * Uniform node representing the light's position.
  38825. *
  38826. * @type {UniformNode<vec3>}
  38827. */
  38828. this.lightPositionNode = lightPosition( light );
  38829. /**
  38830. * A node representing the light's direction.
  38831. *
  38832. * @type {Node<vec3>}
  38833. */
  38834. this.lightDirectionNode = this.lightPositionNode.normalize();
  38835. /**
  38836. * Uniform node representing the light's ground color.
  38837. *
  38838. * @type {UniformNode<vec3>}
  38839. */
  38840. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  38841. }
  38842. /**
  38843. * Overwritten to updated hemisphere light specific uniforms.
  38844. *
  38845. * @param {NodeFrame} frame - A reference to the current node frame.
  38846. */
  38847. update( frame ) {
  38848. const { light } = this;
  38849. super.update( frame );
  38850. this.lightPositionNode.object3d = light;
  38851. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  38852. }
  38853. setup( builder ) {
  38854. const { colorNode, groundColorNode, lightDirectionNode } = this;
  38855. const dotNL = normalWorld.dot( lightDirectionNode );
  38856. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  38857. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  38858. builder.context.irradiance.addAssign( irradiance );
  38859. }
  38860. }
  38861. /**
  38862. * Module for representing spot lights as nodes.
  38863. *
  38864. * @augments AnalyticLightNode
  38865. */
  38866. class SpotLightNode extends AnalyticLightNode {
  38867. static get type() {
  38868. return 'SpotLightNode';
  38869. }
  38870. /**
  38871. * Constructs a new spot light node.
  38872. *
  38873. * @param {?SpotLight} [light=null] - The spot light source.
  38874. */
  38875. constructor( light = null ) {
  38876. super( light );
  38877. /**
  38878. * Uniform node representing the cone cosine.
  38879. *
  38880. * @type {UniformNode<float>}
  38881. */
  38882. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  38883. /**
  38884. * Uniform node representing the penumbra cosine.
  38885. *
  38886. * @type {UniformNode<float>}
  38887. */
  38888. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  38889. /**
  38890. * Uniform node representing the cutoff distance.
  38891. *
  38892. * @type {UniformNode<float>}
  38893. */
  38894. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  38895. /**
  38896. * Uniform node representing the decay exponent.
  38897. *
  38898. * @type {UniformNode<float>}
  38899. */
  38900. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  38901. /**
  38902. * Uniform node representing the light color.
  38903. *
  38904. * @type {UniformNode<Color>}
  38905. */
  38906. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  38907. }
  38908. /**
  38909. * Overwritten to updated spot light specific uniforms.
  38910. *
  38911. * @param {NodeFrame} frame - A reference to the current node frame.
  38912. */
  38913. update( frame ) {
  38914. super.update( frame );
  38915. const { light } = this;
  38916. this.coneCosNode.value = Math.cos( light.angle );
  38917. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  38918. this.cutoffDistanceNode.value = light.distance;
  38919. this.decayExponentNode.value = light.decay;
  38920. }
  38921. /**
  38922. * Computes the spot attenuation for the given angle.
  38923. *
  38924. * @param {NodeBuilder} builder - The node builder.
  38925. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  38926. * @return {Node<float>} The spot attenuation.
  38927. */
  38928. getSpotAttenuation( builder, angleCosine ) {
  38929. const { coneCosNode, penumbraCosNode } = this;
  38930. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  38931. }
  38932. getLightCoord( builder ) {
  38933. const properties = builder.getNodeProperties( this );
  38934. let projectionUV = properties.projectionUV;
  38935. if ( projectionUV === undefined ) {
  38936. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  38937. properties.projectionUV = projectionUV;
  38938. }
  38939. return projectionUV;
  38940. }
  38941. setupDirect( builder ) {
  38942. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  38943. const lightVector = this.getLightVector( builder );
  38944. const lightDirection = lightVector.normalize();
  38945. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  38946. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  38947. const lightDistance = lightVector.length();
  38948. const lightAttenuation = getDistanceAttenuation( {
  38949. lightDistance,
  38950. cutoffDistance: cutoffDistanceNode,
  38951. decayExponent: decayExponentNode
  38952. } );
  38953. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  38954. let projected, lightCoord;
  38955. if ( light.colorNode ) {
  38956. lightCoord = this.getLightCoord( builder );
  38957. projected = light.colorNode( lightCoord );
  38958. } else if ( light.map ) {
  38959. lightCoord = this.getLightCoord( builder );
  38960. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  38961. }
  38962. if ( projected ) {
  38963. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  38964. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  38965. }
  38966. return { lightColor, lightDirection };
  38967. }
  38968. }
  38969. /**
  38970. * An IES version of the default spot light node.
  38971. *
  38972. * @augments SpotLightNode
  38973. */
  38974. class IESSpotLightNode extends SpotLightNode {
  38975. static get type() {
  38976. return 'IESSpotLightNode';
  38977. }
  38978. /**
  38979. * Constructs a new IES spot light node.
  38980. *
  38981. * @param {?SpotLight} [light=null] - The spot light source.
  38982. */
  38983. constructor( light = null ) {
  38984. super( light );
  38985. /**
  38986. * The texture node representing the IES texture.
  38987. *
  38988. * @type {?TextureNode}
  38989. * @default null
  38990. */
  38991. this._iesTextureNode = null;
  38992. }
  38993. /**
  38994. * Overwrites the default implementation to compute an IES conform spot attenuation.
  38995. *
  38996. * @param {NodeBuilder} builder - The node builder.
  38997. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  38998. * @return {Node<float>} The spot attenuation.
  38999. */
  39000. getSpotAttenuation( builder, angleCosine ) {
  39001. const iesMap = this.light.iesMap;
  39002. let spotAttenuation = null;
  39003. if ( iesMap && iesMap.isTexture === true ) {
  39004. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  39005. this._iesTextureNode = texture( iesMap, vec2( angle, 0 ), 0 );
  39006. spotAttenuation = this._iesTextureNode.r;
  39007. } else {
  39008. spotAttenuation = super.getSpotAttenuation( builder, angleCosine );
  39009. }
  39010. return spotAttenuation;
  39011. }
  39012. /**
  39013. * Overwritten to update the IES spot light texture.
  39014. *
  39015. * @param {NodeFrame} frame - A reference to the current node frame.
  39016. */
  39017. update( frame ) {
  39018. super.update( frame );
  39019. if ( this._iesTextureNode !== null && this.light.iesMap ) {
  39020. this._iesTextureNode.value = this.light.iesMap;
  39021. }
  39022. }
  39023. }
  39024. /**
  39025. * Module for representing light probes as nodes.
  39026. *
  39027. * @augments AnalyticLightNode
  39028. */
  39029. class LightProbeNode extends AnalyticLightNode {
  39030. static get type() {
  39031. return 'LightProbeNode';
  39032. }
  39033. /**
  39034. * Constructs a new light probe node.
  39035. *
  39036. * @param {?LightProbe} [light=null] - The light probe.
  39037. */
  39038. constructor( light = null ) {
  39039. super( light );
  39040. const array = [];
  39041. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  39042. /**
  39043. * Light probe represented as a uniform of spherical harmonics.
  39044. *
  39045. * @type {UniformArrayNode}
  39046. */
  39047. this.lightProbe = uniformArray( array );
  39048. }
  39049. /**
  39050. * Overwritten to updated light probe specific uniforms.
  39051. *
  39052. * @param {NodeFrame} frame - A reference to the current node frame.
  39053. */
  39054. update( frame ) {
  39055. const { light } = this;
  39056. super.update( frame );
  39057. //
  39058. for ( let i = 0; i < 9; i ++ ) {
  39059. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  39060. }
  39061. }
  39062. setup( builder ) {
  39063. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  39064. builder.context.irradiance.addAssign( irradiance );
  39065. }
  39066. }
  39067. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  39068. const d = p.abs().sub( b );
  39069. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  39070. } );
  39071. /**
  39072. * An implementation of a projector light node.
  39073. *
  39074. * @augments SpotLightNode
  39075. */
  39076. class ProjectorLightNode extends SpotLightNode {
  39077. static get type() {
  39078. return 'ProjectorLightNode';
  39079. }
  39080. update( frame ) {
  39081. super.update( frame );
  39082. const light = this.light;
  39083. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  39084. if ( light.aspect === null ) {
  39085. let aspect = 1;
  39086. if ( light.map !== null ) {
  39087. aspect = light.map.width / light.map.height;
  39088. }
  39089. light.shadow.aspect = aspect;
  39090. } else {
  39091. light.shadow.aspect = light.aspect;
  39092. }
  39093. }
  39094. /**
  39095. * Overwrites the default implementation to compute projection attenuation.
  39096. *
  39097. * @param {NodeBuilder} builder - The node builder.
  39098. * @return {Node<float>} The spot attenuation.
  39099. */
  39100. getSpotAttenuation( builder ) {
  39101. const attenuation = float( 0 );
  39102. const penumbraCos = this.penumbraCosNode;
  39103. // compute the fragment's position in the light's clip space
  39104. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  39105. // the sign of w determines whether the current fragment is in front or behind the light.
  39106. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  39107. If( spotLightCoord.w.greaterThan( 0 ), () => {
  39108. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  39109. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  39110. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  39111. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  39112. } );
  39113. return attenuation;
  39114. }
  39115. }
  39116. const _matrix41 = /*@__PURE__*/ new Matrix4();
  39117. const _matrix42 = /*@__PURE__*/ new Matrix4();
  39118. let _ltcLib = null;
  39119. /**
  39120. * Module for representing rect area lights as nodes.
  39121. *
  39122. * @augments AnalyticLightNode
  39123. */
  39124. class RectAreaLightNode extends AnalyticLightNode {
  39125. static get type() {
  39126. return 'RectAreaLightNode';
  39127. }
  39128. /**
  39129. * Constructs a new rect area light node.
  39130. *
  39131. * @param {?RectAreaLight} [light=null] - The rect area light source.
  39132. */
  39133. constructor( light = null ) {
  39134. super( light );
  39135. /**
  39136. * Uniform node representing the half height of the are light.
  39137. *
  39138. * @type {UniformNode<vec3>}
  39139. */
  39140. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  39141. /**
  39142. * Uniform node representing the half width of the are light.
  39143. *
  39144. * @type {UniformNode<vec3>}
  39145. */
  39146. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  39147. /**
  39148. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  39149. * relies on `viewMatrix` which might vary per render call.
  39150. *
  39151. * @type {string}
  39152. * @default 'render'
  39153. */
  39154. this.updateType = NodeUpdateType.RENDER;
  39155. }
  39156. /**
  39157. * Overwritten to updated rect area light specific uniforms.
  39158. *
  39159. * @param {NodeFrame} frame - A reference to the current node frame.
  39160. */
  39161. update( frame ) {
  39162. super.update( frame );
  39163. const { light } = this;
  39164. const viewMatrix = frame.camera.matrixWorldInverse;
  39165. _matrix42.identity();
  39166. _matrix41.copy( light.matrixWorld );
  39167. _matrix41.premultiply( viewMatrix );
  39168. _matrix42.extractRotation( _matrix41 );
  39169. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  39170. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  39171. this.halfWidth.value.applyMatrix4( _matrix42 );
  39172. this.halfHeight.value.applyMatrix4( _matrix42 );
  39173. }
  39174. setupDirectRectArea( builder ) {
  39175. let ltc_1, ltc_2;
  39176. if ( builder.isAvailable( 'float32Filterable' ) ) {
  39177. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  39178. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  39179. } else {
  39180. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  39181. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  39182. }
  39183. const { colorNode, light } = this;
  39184. const lightPosition = lightViewPosition( light );
  39185. return {
  39186. lightColor: colorNode,
  39187. lightPosition,
  39188. halfWidth: this.halfWidth,
  39189. halfHeight: this.halfHeight,
  39190. ltc_1,
  39191. ltc_2
  39192. };
  39193. }
  39194. /**
  39195. * Used to configure the internal BRDF approximation texture data.
  39196. *
  39197. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  39198. */
  39199. static setLTC( ltc ) {
  39200. _ltcLib = ltc;
  39201. }
  39202. }
  39203. /**
  39204. * Base class for node parsers. A derived parser must be implemented
  39205. * for each supported native shader language.
  39206. */
  39207. class NodeParser {
  39208. /**
  39209. * The method parses the given native code an returns a node function.
  39210. *
  39211. * @abstract
  39212. * @param {string} source - The native shader code.
  39213. * @return {NodeFunction} A node function.
  39214. */
  39215. parseFunction( /*source*/ ) {
  39216. warn( 'Abstract function.' );
  39217. }
  39218. }
  39219. /**
  39220. * Base class for node functions. A derived module must be implemented
  39221. * for each supported native shader language. Similar to other `Node*` modules,
  39222. * this class is only relevant during the building process and not used
  39223. * in user-level code.
  39224. */
  39225. class NodeFunction {
  39226. /**
  39227. * Constructs a new node function.
  39228. *
  39229. * @param {string} type - The node type. This type is the return type of the node function.
  39230. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  39231. * @param {string} [name=''] - The function's name.
  39232. * @param {string} [precision=''] - The precision qualifier.
  39233. */
  39234. constructor( type, inputs, name = '', precision = '' ) {
  39235. /**
  39236. * The node type. This type is the return type of the node function.
  39237. *
  39238. * @type {string}
  39239. */
  39240. this.type = type;
  39241. /**
  39242. * The function's inputs.
  39243. *
  39244. * @type {Array<NodeFunctionInput>}
  39245. */
  39246. this.inputs = inputs;
  39247. /**
  39248. * The name of the uniform.
  39249. *
  39250. * @type {string}
  39251. * @default ''
  39252. */
  39253. this.name = name;
  39254. /**
  39255. * The precision qualifier.
  39256. *
  39257. * @type {string}
  39258. * @default ''
  39259. */
  39260. this.precision = precision;
  39261. }
  39262. /**
  39263. * This method returns the native code of the node function.
  39264. *
  39265. * @abstract
  39266. * @param {string} name - The function's name.
  39267. * @return {string} A shader code.
  39268. */
  39269. getCode( /*name = this.name*/ ) {
  39270. warn( 'Abstract function.' );
  39271. }
  39272. }
  39273. NodeFunction.isNodeFunction = true;
  39274. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  39275. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  39276. const pragmaMain = '#pragma main';
  39277. const parse$1 = ( source ) => {
  39278. source = source.trim();
  39279. const pragmaMainIndex = source.indexOf( pragmaMain );
  39280. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  39281. const declaration = mainCode.match( declarationRegexp$1 );
  39282. if ( declaration !== null && declaration.length === 5 ) {
  39283. // tokenizer
  39284. const inputsCode = declaration[ 4 ];
  39285. const propsMatches = [];
  39286. let nameMatch = null;
  39287. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  39288. propsMatches.push( nameMatch );
  39289. }
  39290. // parser
  39291. const inputs = [];
  39292. let i = 0;
  39293. while ( i < propsMatches.length ) {
  39294. const isConst = propsMatches[ i ][ 0 ] === 'const';
  39295. if ( isConst === true ) {
  39296. i ++;
  39297. }
  39298. let qualifier = propsMatches[ i ][ 0 ];
  39299. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  39300. i ++;
  39301. } else {
  39302. qualifier = '';
  39303. }
  39304. const type = propsMatches[ i ++ ][ 0 ];
  39305. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  39306. if ( Number.isNaN( count ) === false ) i ++;
  39307. else count = null;
  39308. const name = propsMatches[ i ++ ][ 0 ];
  39309. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  39310. }
  39311. //
  39312. const blockCode = mainCode.substring( declaration[ 0 ].length );
  39313. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  39314. const type = declaration[ 2 ];
  39315. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  39316. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  39317. return {
  39318. type,
  39319. inputs,
  39320. name,
  39321. precision,
  39322. inputsCode,
  39323. blockCode,
  39324. headerCode
  39325. };
  39326. } else {
  39327. throw new Error( 'THREE.FunctionNode: Function is not a GLSL code.' );
  39328. }
  39329. };
  39330. /**
  39331. * This class represents a GLSL node function.
  39332. *
  39333. * @augments NodeFunction
  39334. */
  39335. class GLSLNodeFunction extends NodeFunction {
  39336. /**
  39337. * Constructs a new GLSL node function.
  39338. *
  39339. * @param {string} source - The GLSL source.
  39340. */
  39341. constructor( source ) {
  39342. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  39343. super( type, inputs, name, precision );
  39344. this.inputsCode = inputsCode;
  39345. this.blockCode = blockCode;
  39346. this.headerCode = headerCode;
  39347. }
  39348. /**
  39349. * This method returns the GLSL code of the node function.
  39350. *
  39351. * @param {string} [name=this.name] - The function's name.
  39352. * @return {string} The shader code.
  39353. */
  39354. getCode( name = this.name ) {
  39355. let code;
  39356. const blockCode = this.blockCode;
  39357. if ( blockCode !== '' ) {
  39358. const { type, inputsCode, headerCode, precision } = this;
  39359. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  39360. if ( precision !== '' ) {
  39361. declarationCode = `${ precision } ${ declarationCode }`;
  39362. }
  39363. code = headerCode + declarationCode + blockCode;
  39364. } else {
  39365. // interface function
  39366. code = '';
  39367. }
  39368. return code;
  39369. }
  39370. }
  39371. /**
  39372. * A GLSL node parser.
  39373. *
  39374. * @augments NodeParser
  39375. */
  39376. class GLSLNodeParser extends NodeParser {
  39377. /**
  39378. * The method parses the given GLSL code an returns a node function.
  39379. *
  39380. * @param {string} source - The GLSL code.
  39381. * @return {GLSLNodeFunction} A node function.
  39382. */
  39383. parseFunction( source ) {
  39384. return new GLSLNodeFunction( source );
  39385. }
  39386. }
  39387. const _chainKeys$1 = [];
  39388. const _cacheKeyValues = [];
  39389. // Dedicated uniform for output pass array layer selection
  39390. // This is separate from cameraIndex to avoid the sharedUniformGroup complexity
  39391. const _outputLayerIndex = /*@__PURE__*/ uniform( 0, 'int' ).setGroup( renderGroup );
  39392. /**
  39393. * This renderer module manages node-related objects and is the
  39394. * primary interface between the renderer and the node system.
  39395. *
  39396. * @private
  39397. * @augments DataMap
  39398. */
  39399. class NodeManager extends DataMap {
  39400. /**
  39401. * Constructs a new nodes management component.
  39402. *
  39403. * @param {Renderer} renderer - The renderer.
  39404. * @param {Backend} backend - The renderer's backend.
  39405. */
  39406. constructor( renderer, backend ) {
  39407. super();
  39408. /**
  39409. * The renderer.
  39410. *
  39411. * @type {Renderer}
  39412. */
  39413. this.renderer = renderer;
  39414. /**
  39415. * The renderer's backend.
  39416. *
  39417. * @type {Backend}
  39418. */
  39419. this.backend = backend;
  39420. /**
  39421. * The node frame.
  39422. *
  39423. * @type {Renderer}
  39424. */
  39425. this.nodeFrame = new NodeFrame();
  39426. /**
  39427. * A cache for managing node builder states.
  39428. *
  39429. * @type {Map<number,NodeBuilderState>}
  39430. */
  39431. this.nodeBuilderCache = new Map();
  39432. /**
  39433. * A cache for managing data cache key data.
  39434. *
  39435. * @type {ChainMap}
  39436. */
  39437. this.callHashCache = new ChainMap();
  39438. /**
  39439. * A cache for managing node uniforms group data.
  39440. *
  39441. * @type {ChainMap}
  39442. */
  39443. this.groupsData = new ChainMap();
  39444. /**
  39445. * Queue for pending async builds to limit concurrent compilation.
  39446. *
  39447. * @private
  39448. * @type {Array<Function>}
  39449. */
  39450. this._buildQueue = [];
  39451. /**
  39452. * Whether an async build is currently in progress.
  39453. *
  39454. * @private
  39455. * @type {boolean}
  39456. */
  39457. this._buildInProgress = false;
  39458. /**
  39459. * A cache for managing node objects of
  39460. * scene properties like fog or environments.
  39461. *
  39462. * @type {Object<string,WeakMap>}
  39463. */
  39464. this.cacheLib = {};
  39465. }
  39466. /**
  39467. * Returns `true` if the given node uniforms group must be updated or not.
  39468. *
  39469. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  39470. * @return {boolean} Whether the node uniforms group requires an update or not.
  39471. */
  39472. updateGroup( nodeUniformsGroup ) {
  39473. const groupNode = nodeUniformsGroup.groupNode;
  39474. // groups that are updated per object always require an update so no further checks are needed
  39475. if ( groupNode.updateType === NodeUpdateType.OBJECT ) return true;
  39476. // check for update
  39477. _chainKeys$1[ 0 ] = groupNode;
  39478. _chainKeys$1[ 1 ] = nodeUniformsGroup;
  39479. let groupData = this.groupsData.get( _chainKeys$1 );
  39480. if ( groupData === undefined ) this.groupsData.set( _chainKeys$1, groupData = {} );
  39481. _chainKeys$1[ 0 ] = null;
  39482. _chainKeys$1[ 1 ] = null;
  39483. if ( groupData.version !== groupNode.version ) {
  39484. groupData.version = groupNode.version;
  39485. return true;
  39486. }
  39487. return false;
  39488. }
  39489. /**
  39490. * Returns the cache key for the given render object.
  39491. *
  39492. * @param {RenderObject} renderObject - The render object.
  39493. * @return {number} The cache key.
  39494. */
  39495. getForRenderCacheKey( renderObject ) {
  39496. return renderObject.initialCacheKey;
  39497. }
  39498. /**
  39499. * Creates a node builder configured for the given render object and material.
  39500. *
  39501. * @private
  39502. * @param {RenderObject} renderObject - The render object.
  39503. * @param {Material} material - The material to use.
  39504. * @return {NodeBuilder} The configured node builder.
  39505. */
  39506. _createNodeBuilder( renderObject, material ) {
  39507. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  39508. nodeBuilder.scene = renderObject.scene;
  39509. nodeBuilder.material = material;
  39510. nodeBuilder.camera = renderObject.camera;
  39511. nodeBuilder.context.material = material;
  39512. nodeBuilder.lightsNode = renderObject.lightsNode;
  39513. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  39514. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  39515. nodeBuilder.clippingContext = renderObject.clippingContext;
  39516. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  39517. nodeBuilder.enableMultiview();
  39518. }
  39519. return nodeBuilder;
  39520. }
  39521. /**
  39522. * Returns a node builder state for the given render object.
  39523. *
  39524. * @param {RenderObject} renderObject - The render object.
  39525. * @param {boolean} [useAsync=false] - Whether to use async build with yielding.
  39526. * @return {NodeBuilderState|Promise<NodeBuilderState>} The node builder state (or Promise if async).
  39527. */
  39528. getForRender( renderObject, useAsync = false ) {
  39529. const renderObjectData = this.get( renderObject );
  39530. let nodeBuilderState = renderObjectData.nodeBuilderState;
  39531. if ( nodeBuilderState === undefined ) {
  39532. const { nodeBuilderCache } = this;
  39533. const cacheKey = this.getForRenderCacheKey( renderObject );
  39534. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  39535. if ( nodeBuilderState === undefined ) {
  39536. const buildNodeBuilder = async () => {
  39537. let nodeBuilder = this._createNodeBuilder( renderObject, renderObject.material );
  39538. try {
  39539. if ( useAsync ) {
  39540. await nodeBuilder.buildAsync();
  39541. } else {
  39542. nodeBuilder.build();
  39543. }
  39544. } catch ( e ) {
  39545. nodeBuilder = this._createNodeBuilder( renderObject, new NodeMaterial() );
  39546. if ( useAsync ) {
  39547. await nodeBuilder.buildAsync();
  39548. } else {
  39549. nodeBuilder.build();
  39550. }
  39551. error( 'TSL: ' + e );
  39552. }
  39553. return nodeBuilder;
  39554. };
  39555. if ( useAsync ) {
  39556. return buildNodeBuilder().then( ( nodeBuilder ) => {
  39557. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  39558. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  39559. nodeBuilderState.usedTimes ++;
  39560. renderObjectData.nodeBuilderState = nodeBuilderState;
  39561. return nodeBuilderState;
  39562. } );
  39563. } else {
  39564. // Synchronous path - call buildNodeBuilder but don't await
  39565. let nodeBuilder = this._createNodeBuilder( renderObject, renderObject.material );
  39566. try {
  39567. nodeBuilder.build();
  39568. } catch ( e ) {
  39569. nodeBuilder = this._createNodeBuilder( renderObject, new NodeMaterial() );
  39570. nodeBuilder.build();
  39571. let stackTrace = e.stackTrace;
  39572. if ( ! stackTrace && e.stack ) {
  39573. // Capture stack trace for JavaScript errors
  39574. stackTrace = new StackTrace( e.stack );
  39575. }
  39576. error( 'TSL: ' + e, stackTrace );
  39577. }
  39578. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  39579. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  39580. }
  39581. }
  39582. nodeBuilderState.usedTimes ++;
  39583. renderObjectData.nodeBuilderState = nodeBuilderState;
  39584. }
  39585. return nodeBuilderState;
  39586. }
  39587. /**
  39588. * Async version of getForRender() that yields to main thread during build.
  39589. * Use this in compileAsync() to prevent blocking the main thread.
  39590. *
  39591. * @param {RenderObject} renderObject - The render object.
  39592. * @return {Promise<NodeBuilderState>} A promise that resolves to the node builder state.
  39593. */
  39594. getForRenderAsync( renderObject ) {
  39595. const result = this.getForRender( renderObject, true );
  39596. // Ensure we always return a Promise (cache hit returns nodeBuilderState directly)
  39597. if ( result.then ) {
  39598. return result;
  39599. }
  39600. return Promise.resolve( result );
  39601. }
  39602. /**
  39603. * Returns nodeBuilderState if ready, null if pending async build.
  39604. * Queues async build on first call for cache miss.
  39605. * Use this in render() path to enable non-blocking compilation.
  39606. *
  39607. * @param {RenderObject} renderObject - The render object.
  39608. * @return {?NodeBuilderState} The node builder state, or null if still building.
  39609. */
  39610. getForRenderDeferred( renderObject ) {
  39611. const renderObjectData = this.get( renderObject );
  39612. // Already built for this renderObject
  39613. if ( renderObjectData.nodeBuilderState !== undefined ) {
  39614. return renderObjectData.nodeBuilderState;
  39615. }
  39616. // Check cache with stable key
  39617. const cacheKey = this.getForRenderCacheKey( renderObject );
  39618. const nodeBuilderState = this.nodeBuilderCache.get( cacheKey );
  39619. if ( nodeBuilderState !== undefined ) {
  39620. // Cache hit - use it
  39621. nodeBuilderState.usedTimes ++;
  39622. renderObjectData.nodeBuilderState = nodeBuilderState;
  39623. return nodeBuilderState;
  39624. }
  39625. // Cache miss - check if async build already queued
  39626. if ( renderObjectData.pendingBuild !== true ) {
  39627. // Mark as pending and add to build queue
  39628. renderObjectData.pendingBuild = true;
  39629. this._buildQueue.push( () => {
  39630. return this.getForRenderAsync( renderObject ).then( () => {
  39631. renderObjectData.pendingBuild = false;
  39632. } );
  39633. } );
  39634. // Start processing queue if not already running
  39635. this._processBuildQueue();
  39636. }
  39637. return null; // Not ready
  39638. }
  39639. /**
  39640. * Processes the build queue one item at a time.
  39641. * This ensures builds don't all run simultaneously and freeze the main thread.
  39642. *
  39643. * @private
  39644. */
  39645. _processBuildQueue() {
  39646. if ( this._buildInProgress || this._buildQueue.length === 0 ) {
  39647. return;
  39648. }
  39649. this._buildInProgress = true;
  39650. const buildFn = this._buildQueue.shift();
  39651. buildFn().then( () => {
  39652. this._buildInProgress = false;
  39653. // Process next item in queue
  39654. this._processBuildQueue();
  39655. } );
  39656. }
  39657. /**
  39658. * Deletes the given object from the internal data map
  39659. *
  39660. * @param {any} object - The object to delete.
  39661. * @return {?Object} The deleted dictionary.
  39662. */
  39663. delete( object ) {
  39664. if ( object.isRenderObject ) {
  39665. const nodeBuilderState = this.get( object ).nodeBuilderState;
  39666. if ( nodeBuilderState !== undefined ) {
  39667. nodeBuilderState.usedTimes --;
  39668. if ( nodeBuilderState.usedTimes === 0 ) {
  39669. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  39670. }
  39671. }
  39672. }
  39673. return super.delete( object );
  39674. }
  39675. /**
  39676. * Returns a node builder state for the given compute node.
  39677. *
  39678. * @param {Node} computeNode - The compute node.
  39679. * @return {NodeBuilderState} The node builder state.
  39680. */
  39681. getForCompute( computeNode ) {
  39682. const computeData = this.get( computeNode );
  39683. let nodeBuilderState = computeData.nodeBuilderState;
  39684. if ( nodeBuilderState === undefined || computeData.version !== computeNode.version ) {
  39685. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  39686. nodeBuilder.build();
  39687. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  39688. computeData.nodeBuilderState = nodeBuilderState;
  39689. computeData.version = computeNode.version;
  39690. }
  39691. return nodeBuilderState;
  39692. }
  39693. /**
  39694. * Creates a node builder state for the given node builder.
  39695. *
  39696. * @private
  39697. * @param {NodeBuilder} nodeBuilder - The node builder.
  39698. * @return {NodeBuilderState} The node builder state.
  39699. */
  39700. _createNodeBuilderState( nodeBuilder ) {
  39701. return new NodeBuilderState(
  39702. nodeBuilder.vertexShader,
  39703. nodeBuilder.fragmentShader,
  39704. nodeBuilder.computeShader,
  39705. nodeBuilder.getAttributesArray(),
  39706. nodeBuilder.getBindings(),
  39707. nodeBuilder.updateNodes,
  39708. nodeBuilder.updateBeforeNodes,
  39709. nodeBuilder.updateAfterNodes,
  39710. nodeBuilder.observer,
  39711. nodeBuilder.hardwareClipping,
  39712. nodeBuilder.transforms
  39713. );
  39714. }
  39715. /**
  39716. * Returns an environment node for the current configured
  39717. * scene environment.
  39718. *
  39719. * @param {Scene} scene - The scene.
  39720. * @return {Node} A node representing the current scene environment.
  39721. */
  39722. getEnvironmentNode( scene ) {
  39723. if ( this.renderer.lighting.enabled === false ) return null;
  39724. this.updateEnvironment( scene );
  39725. let environmentNode = null;
  39726. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  39727. environmentNode = scene.environmentNode;
  39728. } else {
  39729. const sceneData = this.get( scene );
  39730. if ( sceneData.environmentNode ) {
  39731. environmentNode = sceneData.environmentNode;
  39732. }
  39733. }
  39734. return environmentNode;
  39735. }
  39736. /**
  39737. * Returns a background node for the current configured
  39738. * scene background.
  39739. *
  39740. * @param {Scene} scene - The scene.
  39741. * @return {Node} A node representing the current scene background.
  39742. */
  39743. getBackgroundNode( scene ) {
  39744. this.updateBackground( scene );
  39745. let backgroundNode = null;
  39746. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  39747. backgroundNode = scene.backgroundNode;
  39748. } else {
  39749. const sceneData = this.get( scene );
  39750. if ( sceneData.backgroundNode ) {
  39751. backgroundNode = sceneData.backgroundNode;
  39752. }
  39753. }
  39754. return backgroundNode;
  39755. }
  39756. /**
  39757. * Returns a fog node for the current configured scene fog.
  39758. *
  39759. * @param {Scene} scene - The scene.
  39760. * @return {Node} A node representing the current scene fog.
  39761. */
  39762. getFogNode( scene ) {
  39763. this.updateFog( scene );
  39764. return scene.fogNode || this.get( scene ).fogNode || null;
  39765. }
  39766. /**
  39767. * Returns a cache key for the given scene and lights node.
  39768. * This key is used by `RenderObject` as a part of the dynamic
  39769. * cache key (a key that must be checked every time the render
  39770. * objects is drawn).
  39771. *
  39772. * @param {Scene} scene - The scene.
  39773. * @param {LightsNode} lightsNode - The lights node.
  39774. * @return {number} The cache key.
  39775. */
  39776. getCacheKey( scene, lightsNode ) {
  39777. _chainKeys$1[ 0 ] = scene;
  39778. _chainKeys$1[ 1 ] = lightsNode;
  39779. const callId = this.renderer.info.calls;
  39780. const cacheKeyData = this.callHashCache.get( _chainKeys$1 ) || {};
  39781. if ( cacheKeyData.callId !== callId ) {
  39782. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  39783. _cacheKeyValues.push( this.renderer.lighting.enabled ? 1 : 0 );
  39784. if ( this.renderer.lighting.enabled ) {
  39785. _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  39786. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  39787. _cacheKeyValues.push( this.renderer.shadowMap.type );
  39788. const environmentNode = this.getEnvironmentNode( scene );
  39789. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  39790. }
  39791. const fogNode = this.getFogNode( scene );
  39792. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  39793. cacheKeyData.callId = callId;
  39794. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  39795. this.callHashCache.set( _chainKeys$1, cacheKeyData );
  39796. _cacheKeyValues.length = 0;
  39797. }
  39798. _chainKeys$1[ 0 ] = null;
  39799. _chainKeys$1[ 1 ] = null;
  39800. return cacheKeyData.cacheKey;
  39801. }
  39802. /**
  39803. * A boolean that indicates whether tone mapping should be enabled
  39804. * or not.
  39805. *
  39806. * @type {boolean}
  39807. */
  39808. get isToneMappingState() {
  39809. return this.renderer.getRenderTarget() ? false : true;
  39810. }
  39811. /**
  39812. * If a scene background is configured, this method makes sure to
  39813. * represent the background with a corresponding node-based implementation.
  39814. *
  39815. * @param {Scene} scene - The scene.
  39816. */
  39817. updateBackground( scene ) {
  39818. const sceneData = this.get( scene );
  39819. const background = scene.background;
  39820. if ( background ) {
  39821. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  39822. if ( sceneData.background !== background || forceUpdate ) {
  39823. const backgroundNode = this.getCacheNode( 'background', background, () => {
  39824. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  39825. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  39826. return pmremTexture( background );
  39827. } else {
  39828. let envMap;
  39829. if ( background.isCubeTexture === true ) {
  39830. envMap = cubeTexture( background );
  39831. } else {
  39832. envMap = texture( background );
  39833. }
  39834. return cubeMapNode( envMap );
  39835. }
  39836. } else if ( background.isTexture === true ) {
  39837. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  39838. } else if ( background.isColor !== true ) {
  39839. error( 'WebGPUNodes: Unsupported background configuration.', background );
  39840. }
  39841. }, forceUpdate );
  39842. sceneData.backgroundNode = backgroundNode;
  39843. sceneData.background = background;
  39844. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  39845. }
  39846. } else if ( sceneData.backgroundNode ) {
  39847. delete sceneData.backgroundNode;
  39848. delete sceneData.background;
  39849. }
  39850. }
  39851. /**
  39852. * This method is part of the caching of nodes which are used to represents the
  39853. * scene's background, fog or environment.
  39854. *
  39855. * @param {string} type - The type of object to cache.
  39856. * @param {Object} object - The object.
  39857. * @param {Function} callback - A callback that produces a node representation for the given object.
  39858. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  39859. * @return {Node} The node representation.
  39860. */
  39861. getCacheNode( type, object, callback, forceUpdate = false ) {
  39862. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  39863. let node = nodeCache.get( object );
  39864. if ( node === undefined || forceUpdate ) {
  39865. node = callback();
  39866. nodeCache.set( object, node );
  39867. }
  39868. return node;
  39869. }
  39870. /**
  39871. * If a scene fog is configured, this method makes sure to
  39872. * represent the fog with a corresponding node-based implementation.
  39873. *
  39874. * @param {Scene} scene - The scene.
  39875. */
  39876. updateFog( scene ) {
  39877. const sceneData = this.get( scene );
  39878. const sceneFog = scene.fog;
  39879. if ( sceneFog ) {
  39880. if ( sceneData.fog !== sceneFog ) {
  39881. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  39882. if ( sceneFog.isFogExp2 ) {
  39883. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  39884. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  39885. return fog( color, densityFogFactor( density ) );
  39886. } else if ( sceneFog.isFog ) {
  39887. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  39888. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  39889. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  39890. return fog( color, rangeFogFactor( near, far ) );
  39891. } else {
  39892. error( 'Renderer: Unsupported fog configuration.', sceneFog );
  39893. }
  39894. } );
  39895. sceneData.fogNode = fogNode;
  39896. sceneData.fog = sceneFog;
  39897. }
  39898. } else {
  39899. delete sceneData.fogNode;
  39900. delete sceneData.fog;
  39901. }
  39902. }
  39903. /**
  39904. * If a scene environment is configured, this method makes sure to
  39905. * represent the environment with a corresponding node-based implementation.
  39906. *
  39907. * @param {Scene} scene - The scene.
  39908. */
  39909. updateEnvironment( scene ) {
  39910. const sceneData = this.get( scene );
  39911. const environment = scene.environment;
  39912. if ( environment ) {
  39913. if ( sceneData.environment !== environment ) {
  39914. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  39915. if ( environment.isCubeTexture === true ) {
  39916. return cubeTexture( environment );
  39917. } else if ( environment.isTexture === true ) {
  39918. return texture( environment );
  39919. } else {
  39920. error( 'Nodes: Unsupported environment configuration.', environment );
  39921. }
  39922. } );
  39923. sceneData.environmentNode = environmentNode;
  39924. sceneData.environment = environment;
  39925. }
  39926. } else if ( sceneData.environmentNode ) {
  39927. delete sceneData.environmentNode;
  39928. delete sceneData.environment;
  39929. }
  39930. }
  39931. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  39932. const nodeFrame = this.nodeFrame;
  39933. nodeFrame.renderer = renderer;
  39934. nodeFrame.scene = scene;
  39935. nodeFrame.object = object;
  39936. nodeFrame.camera = camera;
  39937. nodeFrame.material = material;
  39938. return nodeFrame;
  39939. }
  39940. getNodeFrameForRender( renderObject ) {
  39941. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  39942. }
  39943. /**
  39944. * Returns the current output cache key.
  39945. *
  39946. * @return {string} The output cache key.
  39947. */
  39948. getOutputCacheKey() {
  39949. const renderer = this.renderer;
  39950. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  39951. }
  39952. /**
  39953. * Returns a node that represents the output configuration (tone mapping and
  39954. * color space) for the current target.
  39955. *
  39956. * @param {Texture} outputTarget - The output target.
  39957. * @return {Node} The output node.
  39958. */
  39959. getOutputNode( outputTarget ) {
  39960. const renderer = this.renderer;
  39961. let output;
  39962. if ( outputTarget.isArrayTexture ) {
  39963. if ( this.backend.isWebGLBackend ) {
  39964. output = texture( outputTarget, screenUV ).depth( builtin( 'gl_ViewID_OVR' ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  39965. } else {
  39966. output = texture( outputTarget, screenUV ).depth( _outputLayerIndex ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  39967. }
  39968. } else {
  39969. output = texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  39970. }
  39971. return output;
  39972. }
  39973. /**
  39974. * Sets the output layer index for array texture output pass.
  39975. * This should be called before each layer render during the output pass.
  39976. *
  39977. * @param {number} index - The layer index.
  39978. */
  39979. setOutputLayerIndex( index ) {
  39980. _outputLayerIndex.value = index;
  39981. }
  39982. /**
  39983. * Triggers the call of `updateBefore()` methods
  39984. * for all nodes of the given render object.
  39985. *
  39986. * @param {RenderObject} renderObject - The render object.
  39987. */
  39988. updateBefore( renderObject ) {
  39989. const nodeBuilder = renderObject.getNodeBuilderState();
  39990. for ( const node of nodeBuilder.updateBeforeNodes ) {
  39991. // update frame state for each node
  39992. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  39993. }
  39994. }
  39995. /**
  39996. * Triggers the call of `updateAfter()` methods
  39997. * for all nodes of the given render object.
  39998. *
  39999. * @param {RenderObject} renderObject - The render object.
  40000. */
  40001. updateAfter( renderObject ) {
  40002. const nodeBuilder = renderObject.getNodeBuilderState();
  40003. for ( const node of nodeBuilder.updateAfterNodes ) {
  40004. // update frame state for each node
  40005. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  40006. }
  40007. }
  40008. /**
  40009. * Triggers the call of `update()` methods
  40010. * for all nodes of the given compute node.
  40011. *
  40012. * @param {Node} computeNode - The compute node.
  40013. */
  40014. updateForCompute( computeNode ) {
  40015. const nodeFrame = this.getNodeFrame();
  40016. const nodeBuilder = this.getForCompute( computeNode );
  40017. for ( const node of nodeBuilder.updateNodes ) {
  40018. nodeFrame.updateNode( node );
  40019. }
  40020. }
  40021. /**
  40022. * Triggers the call of `update()` methods
  40023. * for all nodes of the given render object.
  40024. *
  40025. * @param {RenderObject} renderObject - The render object.
  40026. */
  40027. updateForRender( renderObject ) {
  40028. const nodeFrame = this.getNodeFrameForRender( renderObject );
  40029. const nodeBuilder = renderObject.getNodeBuilderState();
  40030. for ( const node of nodeBuilder.updateNodes ) {
  40031. nodeFrame.updateNode( node );
  40032. }
  40033. }
  40034. /**
  40035. * Returns `true` if the given render object requires a refresh.
  40036. *
  40037. * @param {RenderObject} renderObject - The render object.
  40038. * @return {boolean} Whether the given render object requires a refresh or not.
  40039. */
  40040. needsRefresh( renderObject ) {
  40041. const nodeFrame = this.getNodeFrameForRender( renderObject );
  40042. const monitor = renderObject.getMonitor();
  40043. return monitor.needsRefresh( renderObject, nodeFrame );
  40044. }
  40045. /**
  40046. * Frees the internal resources.
  40047. */
  40048. dispose() {
  40049. super.dispose();
  40050. this.nodeFrame = new NodeFrame();
  40051. this.nodeBuilderCache = new Map();
  40052. this.cacheLib = {};
  40053. }
  40054. }
  40055. const _plane = /*@__PURE__*/ new Plane();
  40056. /**
  40057. * Represents the state that is used to perform clipping via clipping planes.
  40058. * There is a default clipping context for each render context. When the
  40059. * scene holds instances of `ClippingGroup`, there will be a context for each
  40060. * group.
  40061. *
  40062. * @private
  40063. */
  40064. class ClippingContext {
  40065. /**
  40066. * Constructs a new clipping context.
  40067. *
  40068. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  40069. */
  40070. constructor( parentContext = null ) {
  40071. /**
  40072. * The clipping context's version.
  40073. *
  40074. * @type {number}
  40075. * @readonly
  40076. */
  40077. this.version = 0;
  40078. /**
  40079. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  40080. *
  40081. * @type {?boolean}
  40082. * @default null
  40083. */
  40084. this.clipIntersection = null;
  40085. /**
  40086. * The clipping context's cache key.
  40087. *
  40088. * @type {string}
  40089. */
  40090. this.cacheKey = '';
  40091. /**
  40092. * Whether the shadow pass is active or not.
  40093. *
  40094. * @type {boolean}
  40095. * @default false
  40096. */
  40097. this.shadowPass = false;
  40098. /**
  40099. * The view matrix.
  40100. *
  40101. * @type {Matrix4}
  40102. */
  40103. this.viewMatrix = new Matrix4();
  40104. /**
  40105. * The view normal matrix.
  40106. *
  40107. * @type {Matrix3}
  40108. */
  40109. this.viewNormalMatrix = new Matrix3();
  40110. /**
  40111. * Internal cache for maintaining clipping contexts.
  40112. *
  40113. * @type {WeakMap<ClippingGroup,ClippingContext>}
  40114. */
  40115. this.clippingGroupContexts = new WeakMap();
  40116. /**
  40117. * The intersection planes.
  40118. *
  40119. * @type {Array<Vector4>}
  40120. */
  40121. this.intersectionPlanes = [];
  40122. /**
  40123. * The intersection planes.
  40124. *
  40125. * @type {Array<Vector4>}
  40126. */
  40127. this.unionPlanes = [];
  40128. /**
  40129. * The version of the clipping context's parent context.
  40130. *
  40131. * @type {?number}
  40132. * @readonly
  40133. */
  40134. this.parentVersion = null;
  40135. if ( parentContext !== null ) {
  40136. this.viewMatrix = parentContext.viewMatrix;
  40137. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  40138. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  40139. this.shadowPass = parentContext.shadowPass;
  40140. }
  40141. }
  40142. /**
  40143. * Projects the given source clipping planes and writes the result into the
  40144. * destination array.
  40145. *
  40146. * @param {Array<Plane>} source - The source clipping planes.
  40147. * @param {Array<Vector4>} destination - The destination.
  40148. * @param {number} offset - The offset.
  40149. */
  40150. projectPlanes( source, destination, offset ) {
  40151. const l = source.length;
  40152. for ( let i = 0; i < l; i ++ ) {
  40153. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  40154. const v = destination[ offset + i ];
  40155. const normal = _plane.normal;
  40156. v.x = - normal.x;
  40157. v.y = - normal.y;
  40158. v.z = - normal.z;
  40159. v.w = _plane.constant;
  40160. }
  40161. }
  40162. /**
  40163. * Updates the root clipping context of a scene.
  40164. *
  40165. * @param {Scene} scene - The scene.
  40166. * @param {Camera} camera - The camera that is used to render the scene.
  40167. */
  40168. updateGlobal( scene, camera ) {
  40169. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  40170. this.viewMatrix.copy( camera.matrixWorldInverse );
  40171. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  40172. }
  40173. /**
  40174. * Updates the clipping context.
  40175. *
  40176. * @param {ClippingContext} parentContext - The parent context.
  40177. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  40178. */
  40179. update( parentContext, clippingGroup ) {
  40180. let update = false;
  40181. if ( parentContext.version !== this.parentVersion ) {
  40182. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  40183. this.unionPlanes = Array.from( parentContext.unionPlanes );
  40184. this.parentVersion = parentContext.version;
  40185. }
  40186. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  40187. this.clipIntersection = clippingGroup.clipIntersection;
  40188. if ( this.clipIntersection ) {
  40189. this.unionPlanes.length = parentContext.unionPlanes.length;
  40190. } else {
  40191. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  40192. }
  40193. }
  40194. const srcClippingPlanes = clippingGroup.clippingPlanes;
  40195. const l = srcClippingPlanes.length;
  40196. let dstClippingPlanes;
  40197. let offset;
  40198. if ( this.clipIntersection ) {
  40199. dstClippingPlanes = this.intersectionPlanes;
  40200. offset = parentContext.intersectionPlanes.length;
  40201. } else {
  40202. dstClippingPlanes = this.unionPlanes;
  40203. offset = parentContext.unionPlanes.length;
  40204. }
  40205. if ( dstClippingPlanes.length !== offset + l ) {
  40206. dstClippingPlanes.length = offset + l;
  40207. for ( let i = 0; i < l; i ++ ) {
  40208. dstClippingPlanes[ offset + i ] = new Vector4();
  40209. }
  40210. update = true;
  40211. }
  40212. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  40213. if ( update ) {
  40214. this.version ++;
  40215. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  40216. }
  40217. }
  40218. /**
  40219. * Returns a clipping context for the given clipping group.
  40220. *
  40221. * @param {ClippingGroup} clippingGroup - The clipping group.
  40222. * @return {ClippingContext} The clipping context.
  40223. */
  40224. getGroupContext( clippingGroup ) {
  40225. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  40226. let context = this.clippingGroupContexts.get( clippingGroup );
  40227. if ( context === undefined ) {
  40228. context = new ClippingContext( this );
  40229. this.clippingGroupContexts.set( clippingGroup, context );
  40230. }
  40231. context.update( this, clippingGroup );
  40232. return context;
  40233. }
  40234. /**
  40235. * The count of union clipping planes.
  40236. *
  40237. * @type {number}
  40238. * @readonly
  40239. */
  40240. get unionClippingCount() {
  40241. return this.unionPlanes.length;
  40242. }
  40243. }
  40244. /**
  40245. * This module is used to represent render bundles inside the renderer
  40246. * for further processing.
  40247. *
  40248. * @private
  40249. */
  40250. class RenderBundle {
  40251. /**
  40252. * Constructs a new bundle group.
  40253. *
  40254. * @param {BundleGroup} bundleGroup - The bundle group.
  40255. * @param {Camera} camera - The camera the bundle group is rendered with.
  40256. * @param {RenderContext} renderContext - The render context the bundle is rendered with.
  40257. */
  40258. constructor( bundleGroup, camera, renderContext ) {
  40259. this.bundleGroup = bundleGroup;
  40260. this.camera = camera;
  40261. this.renderContext = renderContext;
  40262. }
  40263. }
  40264. const _chainKeys = [];
  40265. /**
  40266. * This renderer module manages render bundles.
  40267. *
  40268. * @private
  40269. */
  40270. class RenderBundles {
  40271. /**
  40272. * Constructs a new render bundle management component.
  40273. */
  40274. constructor() {
  40275. /**
  40276. * A chain map for maintaining the render bundles.
  40277. *
  40278. * @type {ChainMap}
  40279. */
  40280. this.bundles = new ChainMap();
  40281. }
  40282. /**
  40283. * Returns a render bundle for the given bundle group and camera.
  40284. *
  40285. * @param {BundleGroup} bundleGroup - The bundle group.
  40286. * @param {Camera} camera - The camera the bundle group is rendered with.
  40287. * @param {RenderContext} renderContext - The render context the bundle is rendered with.
  40288. * @return {RenderBundle} The render bundle.
  40289. */
  40290. get( bundleGroup, camera, renderContext ) {
  40291. const bundles = this.bundles;
  40292. _chainKeys[ 0 ] = bundleGroup;
  40293. _chainKeys[ 1 ] = camera;
  40294. _chainKeys[ 2 ] = renderContext;
  40295. let bundle = bundles.get( _chainKeys );
  40296. if ( bundle === undefined ) {
  40297. bundle = new RenderBundle( bundleGroup, camera, renderContext );
  40298. bundles.set( _chainKeys, bundle );
  40299. }
  40300. _chainKeys[ 0 ] = null;
  40301. _chainKeys[ 1 ] = null;
  40302. _chainKeys[ 2 ] = null;
  40303. return bundle;
  40304. }
  40305. /**
  40306. * Frees all internal resources.
  40307. */
  40308. dispose() {
  40309. this.bundles = new ChainMap();
  40310. }
  40311. }
  40312. /**
  40313. * The purpose of a node library is to assign node implementations
  40314. * to existing library features. In `WebGPURenderer` lights, materials
  40315. * which are not based on `NodeMaterial` as well as tone mapping techniques
  40316. * are implemented with node-based modules.
  40317. *
  40318. * @private
  40319. */
  40320. class NodeLibrary {
  40321. /**
  40322. * Constructs a new node library.
  40323. */
  40324. constructor() {
  40325. /**
  40326. * A weak map that maps lights to light nodes.
  40327. *
  40328. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  40329. */
  40330. this.lightNodes = new WeakMap();
  40331. /**
  40332. * A map that maps materials to node materials.
  40333. *
  40334. * @type {Map<string,NodeMaterial.constructor>}
  40335. */
  40336. this.materialNodes = new Map();
  40337. /**
  40338. * A map that maps tone mapping techniques (constants)
  40339. * to tone mapping node functions.
  40340. *
  40341. * @type {Map<number,Function>}
  40342. */
  40343. this.toneMappingNodes = new Map();
  40344. }
  40345. /**
  40346. * Returns a matching node material instance for the given material object.
  40347. *
  40348. * This method also assigns/copies the properties of the given material object
  40349. * to the node material. This is done to make sure the current material
  40350. * configuration carries over to the node version.
  40351. *
  40352. * @param {Material} material - A material.
  40353. * @return {NodeMaterial} The corresponding node material.
  40354. */
  40355. fromMaterial( material ) {
  40356. if ( material.isNodeMaterial ) return material;
  40357. let nodeMaterial = null;
  40358. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  40359. if ( nodeMaterialClass !== null ) {
  40360. nodeMaterial = new nodeMaterialClass();
  40361. for ( const key in material ) {
  40362. nodeMaterial[ key ] = material[ key ];
  40363. }
  40364. }
  40365. return nodeMaterial;
  40366. }
  40367. /**
  40368. * Adds a tone mapping node function for a tone mapping technique (constant).
  40369. *
  40370. * @param {Function} toneMappingNode - The tone mapping node function.
  40371. * @param {number} toneMapping - The tone mapping.
  40372. */
  40373. addToneMapping( toneMappingNode, toneMapping ) {
  40374. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  40375. }
  40376. /**
  40377. * Returns a tone mapping node function for a tone mapping technique (constant).
  40378. *
  40379. * @param {number} toneMapping - The tone mapping.
  40380. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  40381. */
  40382. getToneMappingFunction( toneMapping ) {
  40383. return this.toneMappingNodes.get( toneMapping ) || null;
  40384. }
  40385. /**
  40386. * Returns a node material class definition for a material type.
  40387. *
  40388. * @param {string} materialType - The material type.
  40389. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  40390. */
  40391. getMaterialNodeClass( materialType ) {
  40392. return this.materialNodes.get( materialType ) || null;
  40393. }
  40394. /**
  40395. * Adds a node material class definition for a given material type.
  40396. *
  40397. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  40398. * @param {string} materialClassType - The material type.
  40399. */
  40400. addMaterial( materialNodeClass, materialClassType ) {
  40401. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  40402. }
  40403. /**
  40404. * Returns a light node class definition for a light class definition.
  40405. *
  40406. * @param {Light.constructor} light - The light class definition.
  40407. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  40408. */
  40409. getLightNodeClass( light ) {
  40410. return this.lightNodes.get( light ) || null;
  40411. }
  40412. /**
  40413. * Adds a light node class definition for a given light class definition.
  40414. *
  40415. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  40416. * @param {Light.constructor} lightClass - The light class definition.
  40417. */
  40418. addLight( lightNodeClass, lightClass ) {
  40419. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  40420. }
  40421. /**
  40422. * Adds a node class definition for the given type to the provided type library.
  40423. *
  40424. * @param {Node.constructor} nodeClass - The node class definition.
  40425. * @param {number|string} type - The object type.
  40426. * @param {Map<number|string,Node.constructor>} library - The type library.
  40427. */
  40428. addType( nodeClass, type, library ) {
  40429. if ( library.has( type ) ) {
  40430. warn( `Redefinition of node ${ type }` );
  40431. return;
  40432. }
  40433. if ( typeof nodeClass !== 'function' ) throw new Error( `THREE.NodeLibrary: Node class ${ nodeClass.name } is not a class.` );
  40434. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `THREE.NodeLibrary: Base class ${ type } is not a class.` );
  40435. library.set( type, nodeClass );
  40436. }
  40437. /**
  40438. * Adds a node class definition for the given class definition to the provided type library.
  40439. *
  40440. * @param {Node.constructor} nodeClass - The node class definition.
  40441. * @param {Node.constructor} baseClass - The class definition.
  40442. * @param {WeakMap<Node.constructor, Node.constructor>} library - The type library.
  40443. */
  40444. addClass( nodeClass, baseClass, library ) {
  40445. if ( library.has( baseClass ) ) {
  40446. warn( `Redefinition of node ${ baseClass.name }` );
  40447. return;
  40448. }
  40449. if ( typeof nodeClass !== 'function' ) throw new Error( `THREE.NodeLibrary: Node class ${ nodeClass.name } is not a class.` );
  40450. if ( typeof baseClass !== 'function' ) throw new Error( `THREE.NodeLibrary: Base class ${ baseClass.name } is not a class.` );
  40451. library.set( baseClass, nodeClass );
  40452. }
  40453. }
  40454. const _defaultLights = /*@__PURE__*/ new LightsNode();
  40455. const _weakMap = /*@__PURE__*/ new WeakMap();
  40456. /**
  40457. * This renderer module manages the lights nodes which are unique
  40458. * per scene and camera combination.
  40459. *
  40460. * The lights node itself is later configured in the render list
  40461. * with the actual lights from the scene.
  40462. *
  40463. * @private
  40464. */
  40465. class Lighting {
  40466. /**
  40467. * Constructs a new lighting manager.
  40468. */
  40469. constructor() {
  40470. /**
  40471. * Whether this lighting manager is enabled or not.
  40472. *
  40473. * @type {boolean}
  40474. * @default true
  40475. */
  40476. this.enabled = true;
  40477. /**
  40478. * A stack of light arrays saved per render via {@link Lighting#beginRender}.
  40479. *
  40480. * @private
  40481. * @type {Array<Array<Light>>}
  40482. */
  40483. this._cache = [];
  40484. }
  40485. /**
  40486. * Creates a new lights node for the given array of lights.
  40487. *
  40488. * @param {Array<Light>} lights - The render object.
  40489. * @return {LightsNode} The lights node.
  40490. */
  40491. createNode( lights = [] ) {
  40492. return new LightsNode().setLights( lights );
  40493. }
  40494. /**
  40495. * Returns a lights node for the given scene.
  40496. *
  40497. * @param {Scene} scene - The scene.
  40498. * @return {LightsNode} The lights node.
  40499. */
  40500. getNode( scene ) {
  40501. // Ignore renderable objects, e.g: Mesh, Sprite, etc.
  40502. if ( scene.isScene !== true && scene.isGroup !== true ) return _defaultLights;
  40503. let node = _weakMap.get( scene );
  40504. if ( node === undefined ) {
  40505. node = this.createNode();
  40506. _weakMap.set( scene, node );
  40507. }
  40508. return node;
  40509. }
  40510. /**
  40511. * Saves the current lights of the scene's lights node so they can be restored
  40512. * in {@link Lighting#finishRender}. Must be paired with a `finishRender()` call
  40513. * to avoid memory leaks.
  40514. *
  40515. * Nested render calls might mutate the lights array so a save/restore is required
  40516. * for each render call.
  40517. *
  40518. * @param {Scene} scene - The scene.
  40519. */
  40520. beginRender( scene ) {
  40521. this._cache.push( this.getNode( scene ).getLights() );
  40522. }
  40523. /**
  40524. * Restores the lights saved by the matching {@link Lighting#beginRender} call.
  40525. *
  40526. * @param {Scene} scene - The scene.
  40527. */
  40528. finishRender( scene ) {
  40529. this.getNode( scene ).setLights( this._cache.pop() );
  40530. }
  40531. }
  40532. /**
  40533. * A special type of render target that is used when rendering
  40534. * with the WebXR Device API.
  40535. *
  40536. * @private
  40537. * @augments RenderTarget
  40538. */
  40539. class XRRenderTarget extends RenderTarget {
  40540. /**
  40541. * Constructs a new XR render target.
  40542. *
  40543. * @param {number} [width=1] - The width of the render target.
  40544. * @param {number} [height=1] - The height of the render target.
  40545. * @param {Object} [options={}] - The configuration options.
  40546. */
  40547. constructor( width = 1, height = 1, options = {} ) {
  40548. super( width, height, options );
  40549. /**
  40550. * This flag can be used for type testing.
  40551. *
  40552. * @type {boolean}
  40553. * @readonly
  40554. * @default true
  40555. */
  40556. this.isXRRenderTarget = true;
  40557. /**
  40558. * Whether the attachments of the render target
  40559. * are defined by external textures. This flag is
  40560. * set to `true` when using the WebXR Layers API.
  40561. *
  40562. * @private
  40563. * @type {boolean}
  40564. * @default false
  40565. */
  40566. this._hasExternalTextures = false;
  40567. /**
  40568. * Whether a depth buffer should automatically be allocated
  40569. * for this XR render target or not.
  40570. *
  40571. * Allocating a depth buffer is the default behavior of XR render
  40572. * targets. However, when using the WebXR Layers API, this flag
  40573. * must be set to `false` when the `ignoreDepthValues` property of
  40574. * the projection layers evaluates to `false`.
  40575. *
  40576. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  40577. *
  40578. * @private
  40579. * @type {boolean}
  40580. * @default true
  40581. */
  40582. this._autoAllocateDepthBuffer = true;
  40583. /**
  40584. * Whether this render target is associated with a XRWebGLLayer.
  40585. *
  40586. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  40587. * this means that you don't have access to its bound color,
  40588. * stencil and depth buffers. We need to handle this framebuffer
  40589. * differently since its textures are always bound.
  40590. *
  40591. * @private
  40592. * @type {boolean}
  40593. * @default false
  40594. * */
  40595. this._isOpaqueFramebuffer = false;
  40596. }
  40597. copy( source ) {
  40598. super.copy( source );
  40599. this._hasExternalTextures = source._hasExternalTextures;
  40600. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  40601. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  40602. return this;
  40603. }
  40604. }
  40605. const _cameraLPos = /*@__PURE__*/ new Vector3();
  40606. const _cameraRPos = /*@__PURE__*/ new Vector3();
  40607. const _contextNodeLib = /*@__PURE__*/ new WeakMap();
  40608. /**
  40609. * The XR manager is built on top of the WebXR Device API to
  40610. * manage XR sessions with renderer backends.
  40611. *
  40612. * @augments EventDispatcher
  40613. */
  40614. class XRManager extends EventDispatcher {
  40615. /**
  40616. * Constructs a new XR manager.
  40617. *
  40618. * @param {Renderer} renderer - The renderer.
  40619. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  40620. */
  40621. constructor( renderer, multiview = false ) {
  40622. super();
  40623. /**
  40624. * This flag globally enables XR rendering.
  40625. *
  40626. * @type {boolean}
  40627. * @default false
  40628. */
  40629. this.enabled = false;
  40630. /**
  40631. * Whether the XR device is currently presenting or not.
  40632. *
  40633. * @type {boolean}
  40634. * @default false
  40635. * @readonly
  40636. */
  40637. this.isPresenting = false;
  40638. /**
  40639. * Whether the XR camera should automatically be updated or not.
  40640. *
  40641. * @type {boolean}
  40642. * @default true
  40643. */
  40644. this.cameraAutoUpdate = true;
  40645. /**
  40646. * The renderer.
  40647. *
  40648. * @private
  40649. * @type {Renderer}
  40650. */
  40651. this._renderer = renderer;
  40652. // camera
  40653. /**
  40654. * Represents the camera for the left eye.
  40655. *
  40656. * @private
  40657. * @type {PerspectiveCamera}
  40658. */
  40659. this._cameraL = new PerspectiveCamera();
  40660. this._cameraL.viewport = new Vector4();
  40661. this._cameraL.matrixWorldAutoUpdate = false;
  40662. /**
  40663. * Represents the camera for the right eye.
  40664. *
  40665. * @private
  40666. * @type {PerspectiveCamera}
  40667. */
  40668. this._cameraR = new PerspectiveCamera();
  40669. this._cameraR.viewport = new Vector4();
  40670. this._cameraR.matrixWorldAutoUpdate = false;
  40671. /**
  40672. * A list of cameras used for rendering the XR views.
  40673. *
  40674. * @private
  40675. * @type {Array<Camera>}
  40676. */
  40677. this._cameras = [ this._cameraL, this._cameraR ];
  40678. /**
  40679. * The main XR camera.
  40680. *
  40681. * @private
  40682. * @type {ArrayCamera}
  40683. */
  40684. this._cameraXR = new ArrayCamera();
  40685. /**
  40686. * The current near value of the XR camera.
  40687. *
  40688. * @private
  40689. * @type {?number}
  40690. * @default null
  40691. */
  40692. this._currentDepthNear = null;
  40693. /**
  40694. * The current far value of the XR camera.
  40695. *
  40696. * @private
  40697. * @type {?number}
  40698. * @default null
  40699. */
  40700. this._currentDepthFar = null;
  40701. /**
  40702. * A list of WebXR controllers requested by the application.
  40703. *
  40704. * @private
  40705. * @type {Array<WebXRController>}
  40706. */
  40707. this._controllers = [];
  40708. /**
  40709. * A list of XR input source. Each input source belongs to
  40710. * an instance of WebXRController.
  40711. *
  40712. * @private
  40713. * @type {Array<XRInputSource?>}
  40714. */
  40715. this._controllerInputSources = [];
  40716. /**
  40717. * The XR render target that represents the rendering destination
  40718. * during an active XR session.
  40719. *
  40720. * @private
  40721. * @type {?RenderTarget}
  40722. * @default null
  40723. */
  40724. this._xrRenderTarget = null;
  40725. /**
  40726. * An array holding all the non-projection layers
  40727. *
  40728. * @private
  40729. * @type {Array<Object>}
  40730. * @default []
  40731. */
  40732. this._layers = [];
  40733. /**
  40734. * Whether the XR session uses layers.
  40735. *
  40736. * @private
  40737. * @type {boolean}
  40738. * @default false
  40739. */
  40740. this._sessionUsesLayers = false;
  40741. /**
  40742. * Whether the device supports binding gl objects.
  40743. *
  40744. * @private
  40745. * @type {boolean}
  40746. * @readonly
  40747. */
  40748. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  40749. this._supportsWebGPUBinding = typeof globalThis.XRGPUBinding !== 'undefined';
  40750. /**
  40751. * Helper function to create native WebXR Layer.
  40752. *
  40753. * @private
  40754. * @type {Function}
  40755. */
  40756. this._createXRLayer = createXRLayer.bind( this );
  40757. /**
  40758. * The current WebGL context.
  40759. *
  40760. * @private
  40761. * @type {?WebGL2RenderingContext}
  40762. * @default null
  40763. */
  40764. this._gl = null;
  40765. /**
  40766. * The current animation context.
  40767. *
  40768. * @private
  40769. * @type {?Window}
  40770. * @default null
  40771. */
  40772. this._currentAnimationContext = null;
  40773. /**
  40774. * The current animation loop.
  40775. *
  40776. * @private
  40777. * @type {?Function}
  40778. * @default null
  40779. */
  40780. this._currentAnimationLoop = null;
  40781. /**
  40782. * The current pixel ratio.
  40783. *
  40784. * @private
  40785. * @type {?number}
  40786. * @default null
  40787. */
  40788. this._currentPixelRatio = null;
  40789. /**
  40790. * The renderer's sample count before XR temporarily overrides it.
  40791. *
  40792. * @private
  40793. * @type {?number}
  40794. * @default null
  40795. */
  40796. this._currentSamples = null;
  40797. /**
  40798. * The current size of the renderer's canvas
  40799. * in logical pixel unit.
  40800. *
  40801. * @private
  40802. * @type {Vector2}
  40803. */
  40804. this._currentSize = new Vector2();
  40805. /**
  40806. * The default event listener for handling events inside a XR session.
  40807. *
  40808. * @private
  40809. * @type {Function}
  40810. */
  40811. this._onSessionEvent = onSessionEvent.bind( this );
  40812. /**
  40813. * The event listener for handling the end of a XR session.
  40814. *
  40815. * @private
  40816. * @type {Function}
  40817. */
  40818. this._onSessionEnd = onSessionEnd.bind( this );
  40819. /**
  40820. * The event listener for handling the `inputsourceschange` event.
  40821. *
  40822. * @private
  40823. * @type {Function}
  40824. */
  40825. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  40826. /**
  40827. * The animation loop which is used as a replacement for the default
  40828. * animation loop of the application. It is only used when a XR session
  40829. * is active.
  40830. *
  40831. * @private
  40832. * @type {Function}
  40833. */
  40834. this._onAnimationFrame = onAnimationFrame.bind( this );
  40835. /**
  40836. * The current XR reference space.
  40837. *
  40838. * @private
  40839. * @type {?XRReferenceSpace}
  40840. * @default null
  40841. */
  40842. this._referenceSpace = null;
  40843. /**
  40844. * The current XR reference space type.
  40845. *
  40846. * @private
  40847. * @type {XRReferenceSpaceType}
  40848. * @default 'local-floor'
  40849. */
  40850. this._referenceSpaceType = 'local-floor';
  40851. /**
  40852. * A custom reference space defined by the application.
  40853. *
  40854. * @private
  40855. * @type {?XRReferenceSpace}
  40856. * @default null
  40857. */
  40858. this._customReferenceSpace = null;
  40859. /**
  40860. * The framebuffer scale factor.
  40861. *
  40862. * @private
  40863. * @type {number}
  40864. * @default 1
  40865. */
  40866. this._framebufferScaleFactor = 1;
  40867. /**
  40868. * The foveation factor.
  40869. *
  40870. * @private
  40871. * @type {number}
  40872. * @default 1
  40873. */
  40874. this._foveation = 1.0;
  40875. /**
  40876. * A reference to the current XR session.
  40877. *
  40878. * @private
  40879. * @type {?XRSession}
  40880. * @default null
  40881. */
  40882. this._session = null;
  40883. /**
  40884. * A reference to the current XR base layer.
  40885. *
  40886. * @private
  40887. * @type {?XRWebGLLayer}
  40888. * @default null
  40889. */
  40890. this._glBaseLayer = null;
  40891. /**
  40892. * A reference to the current XR binding.
  40893. *
  40894. * @private
  40895. * @type {?XRWebGLBinding}
  40896. * @default null
  40897. */
  40898. this._glBinding = null;
  40899. /**
  40900. * A reference to the current XR WebGPU binding.
  40901. *
  40902. * @private
  40903. * @type {?XRGPUBinding}
  40904. * @default null
  40905. */
  40906. this._webgpuBinding = null;
  40907. /**
  40908. * A reference to the current XR projection layer.
  40909. *
  40910. * @private
  40911. * @type {?XRProjectionLayer}
  40912. * @default null
  40913. */
  40914. this._glProjLayer = null;
  40915. /**
  40916. * A reference to the current XR frame.
  40917. *
  40918. * @private
  40919. * @type {?XRFrame}
  40920. * @default null
  40921. */
  40922. this._xrFrame = null;
  40923. /**
  40924. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  40925. *
  40926. * Note: this does not represent XRSession explicitly requesting
  40927. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  40928. *
  40929. * @private
  40930. * @type {boolean}
  40931. * @readonly
  40932. */
  40933. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  40934. /**
  40935. * Whether the usage of multiview has been requested by the application or not.
  40936. *
  40937. * @private
  40938. * @type {boolean}
  40939. * @default false
  40940. * @readonly
  40941. */
  40942. this._useMultiviewIfPossible = multiview;
  40943. /**
  40944. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  40945. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  40946. *
  40947. * @private
  40948. * @type {boolean}
  40949. * @readonly
  40950. */
  40951. this._useMultiview = false;
  40952. }
  40953. /**
  40954. * Returns an instance of `THREE.Group` that represents the transformation
  40955. * of a XR controller in target ray space. The requested controller is defined
  40956. * by the given index.
  40957. *
  40958. * @param {number} index - The index of the XR controller.
  40959. * @return {Group} A group that represents the controller's transformation.
  40960. */
  40961. getController( index ) {
  40962. const controller = this._getController( index );
  40963. return controller.getTargetRaySpace();
  40964. }
  40965. /**
  40966. * Returns an instance of `THREE.Group` that represents the transformation
  40967. * of a XR controller in grip space. The requested controller is defined
  40968. * by the given index.
  40969. *
  40970. * @param {number} index - The index of the XR controller.
  40971. * @return {Group} A group that represents the controller's transformation.
  40972. */
  40973. getControllerGrip( index ) {
  40974. const controller = this._getController( index );
  40975. return controller.getGripSpace();
  40976. }
  40977. /**
  40978. * Returns an instance of `THREE.Group` that represents the transformation
  40979. * of a XR controller in hand space. The requested controller is defined
  40980. * by the given index.
  40981. *
  40982. * @param {number} index - The index of the XR controller.
  40983. * @return {Group} A group that represents the controller's transformation.
  40984. */
  40985. getHand( index ) {
  40986. const controller = this._getController( index );
  40987. return controller.getHandSpace();
  40988. }
  40989. /**
  40990. * Returns the foveation value.
  40991. *
  40992. * @return {number|undefined} The foveation value.
  40993. */
  40994. getFoveation() {
  40995. return this._foveation;
  40996. }
  40997. /**
  40998. * Sets the foveation value.
  40999. *
  41000. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  41001. * and `1` means maximum foveation (the edges render at lower resolution).
  41002. */
  41003. setFoveation( foveation ) {
  41004. this._foveation = foveation;
  41005. if ( this._glProjLayer !== null ) {
  41006. this._glProjLayer.fixedFoveation = foveation;
  41007. }
  41008. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  41009. this._glBaseLayer.fixedFoveation = foveation;
  41010. }
  41011. }
  41012. /**
  41013. * Returns the framebuffer scale factor.
  41014. *
  41015. * @return {number} The framebuffer scale factor.
  41016. */
  41017. getFramebufferScaleFactor() {
  41018. return this._framebufferScaleFactor;
  41019. }
  41020. /**
  41021. * Sets the framebuffer scale factor.
  41022. *
  41023. * This method can not be used during a XR session.
  41024. *
  41025. * @param {number} factor - The framebuffer scale factor.
  41026. */
  41027. setFramebufferScaleFactor( factor ) {
  41028. this._framebufferScaleFactor = factor;
  41029. if ( this.isPresenting === true ) {
  41030. warn( 'XRManager: Cannot change framebuffer scale while presenting.' );
  41031. }
  41032. }
  41033. /**
  41034. * Returns the reference space type.
  41035. *
  41036. * @return {XRReferenceSpaceType} The reference space type.
  41037. */
  41038. getReferenceSpaceType() {
  41039. return this._referenceSpaceType;
  41040. }
  41041. /**
  41042. * Sets the reference space type.
  41043. *
  41044. * This method can not be used during a XR session.
  41045. *
  41046. * @param {XRReferenceSpaceType} type - The reference space type.
  41047. */
  41048. setReferenceSpaceType( type ) {
  41049. this._referenceSpaceType = type;
  41050. if ( this.isPresenting === true ) {
  41051. warn( 'XRManager: Cannot change reference space type while presenting.' );
  41052. }
  41053. }
  41054. /**
  41055. * Returns the XR reference space.
  41056. *
  41057. * @return {XRReferenceSpace} The XR reference space.
  41058. */
  41059. getReferenceSpace() {
  41060. return this._customReferenceSpace || this._referenceSpace;
  41061. }
  41062. /**
  41063. * Sets a custom XR reference space.
  41064. *
  41065. * @param {XRReferenceSpace} space - The XR reference space.
  41066. */
  41067. setReferenceSpace( space ) {
  41068. this._customReferenceSpace = space;
  41069. }
  41070. /**
  41071. * Returns the XR camera.
  41072. *
  41073. * @return {ArrayCamera} The XR camera.
  41074. */
  41075. getCamera() {
  41076. return this._cameraXR;
  41077. }
  41078. /**
  41079. * Returns the environment blend mode from the current XR session.
  41080. *
  41081. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  41082. */
  41083. getEnvironmentBlendMode() {
  41084. if ( this._session !== null ) {
  41085. return this._session.environmentBlendMode;
  41086. }
  41087. }
  41088. /**
  41089. * Returns the current base layer.
  41090. *
  41091. * This is an `XRProjectionLayer` when the targeted XR device supports the
  41092. * WebXR Layers API, or an `XRWebGLLayer` otherwise.
  41093. *
  41094. * @return {?(XRWebGLLayer|XRProjectionLayer)} The XR base layer.
  41095. */
  41096. getBaseLayer() {
  41097. return this._glProjLayer !== null ? this._glProjLayer : this._glBaseLayer;
  41098. }
  41099. /**
  41100. * Returns the current XR binding.
  41101. *
  41102. * Creates a new binding if needed and the browser is
  41103. * capable of doing so.
  41104. *
  41105. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  41106. */
  41107. getBinding() {
  41108. if ( this._glBinding === null && this._supportsGlBinding ) {
  41109. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  41110. }
  41111. return this._glBinding;
  41112. }
  41113. /**
  41114. * Applies WebXR fixed foveation to the internal post-processing render target
  41115. * used by the first XR render pass before compositing into a projection layer.
  41116. *
  41117. * Browser-side `XRWebGLBinding.foveateBoundTexture()` failures are treated as
  41118. * non-fatal so they do not interrupt rendering.
  41119. *
  41120. * @param {RenderTarget} renderTarget - The internal render target.
  41121. */
  41122. foveateBoundTexture( renderTarget ) {
  41123. if ( renderTarget.isPostProcessingRenderTarget !== true ) return;
  41124. if ( this.isPresenting !== true ) return;
  41125. if ( this._glProjLayer === null ) return;
  41126. const backend = this._renderer.backend;
  41127. if ( backend === undefined || backend.isWebGLBackend !== true ) return;
  41128. if ( backend.state === null ) return;
  41129. const outputRenderTarget = this._renderer.getOutputRenderTarget();
  41130. if ( outputRenderTarget === null || outputRenderTarget.isXRRenderTarget !== true ) return;
  41131. const glBinding = this.getBinding();
  41132. if ( glBinding === null || typeof glBinding.foveateBoundTexture !== 'function' ) return;
  41133. this._renderer._textures.updateRenderTarget( renderTarget );
  41134. const { textureGPU, glTextureType } = backend.get( renderTarget.texture );
  41135. if ( textureGPU === undefined || glTextureType === undefined ) return;
  41136. if ( renderTarget._xrFoveationTextureGPU === textureGPU ) return;
  41137. renderTarget._xrFoveationTextureGPU = textureGPU;
  41138. backend.state.bindTexture( glTextureType, textureGPU );
  41139. try {
  41140. glBinding.foveateBoundTexture( glTextureType, this.getFoveation() );
  41141. } catch ( error ) {
  41142. warnOnce( `XRManager: Unable to foveate bound XR post-processing texture. ${error.name}: ${error.message}` );
  41143. } finally {
  41144. backend.state.unbindTexture();
  41145. }
  41146. }
  41147. /**
  41148. * Returns the current XR WebGPU binding.
  41149. *
  41150. * Creates a new binding if needed and the browser is
  41151. * capable of doing so.
  41152. *
  41153. * @return {?XRGPUBinding} The XR WebGPU binding. Returns `null` if one cannot be created.
  41154. */
  41155. getWebGPUBinding() {
  41156. if ( this._webgpuBinding === null && this._supportsWebGPUBinding ) {
  41157. this._webgpuBinding = new globalThis.XRGPUBinding( this._session, this._renderer.backend.device );
  41158. }
  41159. return this._webgpuBinding;
  41160. }
  41161. /**
  41162. * Returns whether the current XR session is using WebGPU.
  41163. *
  41164. * @private
  41165. * @return {boolean} Whether the current session uses the WebGPU backend and the `webgpu` session feature.
  41166. */
  41167. _isWebGPUSession() {
  41168. return this._renderer.backend.isWebGPUBackend === true &&
  41169. this._session !== null &&
  41170. this._session.enabledFeatures.includes( 'webgpu' );
  41171. }
  41172. /**
  41173. * Validates the current WebGPU XR session requirements.
  41174. *
  41175. * @private
  41176. */
  41177. _validateWebGPUSession() {
  41178. const renderer = this._renderer;
  41179. if ( renderer.backend.isWebGPUBackend !== true ) return;
  41180. if ( this._session.enabledFeatures.includes( 'webgpu' ) === false ) {
  41181. throw new Error( 'THREE.XRManager: WebGPU XR sessions require the "webgpu" session feature. Use VRButtonGPU/XRButton with "webgpu" enabled or use a WebGL backend.' );
  41182. }
  41183. if ( renderer.samples > 0 ) {
  41184. warnOnce( 'THREE.XRManager: WebGPU XR does not support MSAA yet. Disabling MSAA for this XR session.' );
  41185. if ( this._currentSamples === null ) this._currentSamples = renderer.samples;
  41186. renderer._samples = 0;
  41187. }
  41188. }
  41189. /**
  41190. * Initializes the WebGPU XR projection layer and render target.
  41191. *
  41192. * @private
  41193. * @async
  41194. * @param {XRSession} session - The XR session.
  41195. * @return {Promise<void>}
  41196. */
  41197. async _initWebGPUSession( session ) {
  41198. const webgpuBinding = this.getWebGPUBinding();
  41199. const glProjLayer = webgpuBinding.createProjectionLayer( {
  41200. colorFormat: webgpuBinding.getPreferredColorFormat(),
  41201. depthStencilFormat: 'depth24plus'
  41202. } );
  41203. this._glProjLayer = glProjLayer;
  41204. session.updateRenderState( { layers: [ glProjLayer ] } );
  41205. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  41206. this._xrRenderTarget = new RenderTarget( glProjLayer.textureWidth, glProjLayer.textureHeight, {
  41207. depth: 2,
  41208. minFilter: LinearFilter,
  41209. magFilter: LinearFilter,
  41210. depthBuffer: true,
  41211. multiview: false,
  41212. useArrayDepthTexture: true,
  41213. samples: 0
  41214. } );
  41215. this._xrRenderTarget.texture.isArrayTexture = true;
  41216. if ( this._useMultiviewIfPossible === true ) {
  41217. warnOnce( 'THREE.XRManager: WebGPU XR does not support multiview yet. Disabling multiview for this XR session.' );
  41218. }
  41219. this._useMultiview = false;
  41220. }
  41221. /**
  41222. * Releases WebGPU XR resources associated with the current session.
  41223. *
  41224. * @private
  41225. */
  41226. _disposeWebGPUSession() {
  41227. const renderer = this._renderer;
  41228. const xrRenderTarget = this._xrRenderTarget;
  41229. if ( xrRenderTarget === null || renderer.backend.isWebGPUBackend !== true ) return;
  41230. // XR textures are external (from XRGPUBinding), so clear cached state before disposal.
  41231. const backend = renderer.backend;
  41232. const texturesModule = renderer._textures;
  41233. const renderTargetData = backend.get ? backend.get( xrRenderTarget ) : null;
  41234. if ( renderTargetData ) {
  41235. renderTargetData.descriptors = undefined;
  41236. }
  41237. const deleteResource = ( resource ) => {
  41238. if ( resource === null || resource === undefined ) return;
  41239. if ( backend.delete ) backend.delete( resource );
  41240. if ( texturesModule.delete ) texturesModule.delete( resource );
  41241. };
  41242. for ( let i = 0; i < xrRenderTarget.textures.length; i ++ ) {
  41243. deleteResource( xrRenderTarget.textures[ i ] );
  41244. }
  41245. deleteResource( xrRenderTarget.depthTexture );
  41246. deleteResource( xrRenderTarget );
  41247. if ( renderer._renderContexts && renderer._renderContexts.dispose ) {
  41248. renderer._renderContexts.dispose();
  41249. }
  41250. xrRenderTarget.dispose();
  41251. }
  41252. /**
  41253. * Collects WebGPU XR sub-image data for the current frame.
  41254. *
  41255. * @private
  41256. * @param {Array<XRView>} views - The XR views for the current pose.
  41257. * @return {{colorTexture:?GPUTexture, viewDescriptors:Array<Object>, viewports:Array<XRViewport>}} The WebGPU XR view data.
  41258. */
  41259. _getWebGPUViewData( views ) {
  41260. const webgpuBinding = this.getWebGPUBinding();
  41261. const viewData = {
  41262. colorTexture: null,
  41263. viewDescriptors: [],
  41264. viewports: []
  41265. };
  41266. for ( let i = 0; i < views.length; i ++ ) {
  41267. const gpuSubImage = webgpuBinding.getViewSubImage( this._glProjLayer, views[ i ] );
  41268. if ( viewData.colorTexture === null ) {
  41269. viewData.colorTexture = gpuSubImage.colorTexture;
  41270. }
  41271. viewData.viewports.push( gpuSubImage.viewport );
  41272. if ( gpuSubImage.getViewDescriptor ) {
  41273. viewData.viewDescriptors.push( gpuSubImage.getViewDescriptor() );
  41274. }
  41275. }
  41276. return viewData;
  41277. }
  41278. /**
  41279. * Returns the current XR frame.
  41280. *
  41281. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  41282. */
  41283. getFrame() {
  41284. return this._xrFrame;
  41285. }
  41286. /**
  41287. * Returns `true` if the engine renders to a multiview target.
  41288. *
  41289. * @return {boolean} Whether the engine renders to a multiview render target or not.
  41290. */
  41291. useMultiview() {
  41292. return this._useMultiview;
  41293. }
  41294. /**
  41295. * This method can be used in XR applications to create a quadratic layer that presents a separate
  41296. * rendered scene.
  41297. *
  41298. * @param {number} width - The width of the layer plane in world units.
  41299. * @param {number} height - The height of the layer plane in world units.
  41300. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  41301. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  41302. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  41303. * @param {number} pixelheight - The height of the layer's render target in pixels.
  41304. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  41305. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  41306. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  41307. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  41308. */
  41309. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  41310. const geometry = new PlaneGeometry( width, height );
  41311. const renderTarget = new XRRenderTarget(
  41312. pixelwidth,
  41313. pixelheight,
  41314. {
  41315. format: RGBAFormat,
  41316. type: UnsignedByteType,
  41317. depthTexture: new DepthTexture(
  41318. pixelwidth,
  41319. pixelheight,
  41320. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  41321. undefined,
  41322. undefined,
  41323. undefined,
  41324. undefined,
  41325. undefined,
  41326. undefined,
  41327. attributes.stencil ? DepthStencilFormat : DepthFormat
  41328. ),
  41329. stencilBuffer: attributes.stencil,
  41330. resolveDepthBuffer: false,
  41331. resolveStencilBuffer: false
  41332. } );
  41333. renderTarget._autoAllocateDepthBuffer = true;
  41334. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  41335. material.map = renderTarget.texture;
  41336. material.map.offset.y = 1;
  41337. material.map.repeat.y = -1;
  41338. const plane = new Mesh( geometry, material );
  41339. plane.position.copy( translation );
  41340. plane.quaternion.copy( quaternion );
  41341. const layer = {
  41342. type: 'quad',
  41343. width: width,
  41344. height: height,
  41345. translation: translation,
  41346. quaternion: quaternion,
  41347. pixelwidth: pixelwidth,
  41348. pixelheight: pixelheight,
  41349. plane: plane,
  41350. material: material,
  41351. rendercall: rendercall,
  41352. renderTarget: renderTarget };
  41353. this._layers.push( layer );
  41354. if ( this._session !== null ) {
  41355. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  41356. layer.plane.material.blending = CustomBlending;
  41357. layer.plane.material.blendEquation = AddEquation;
  41358. layer.plane.material.blendSrc = ZeroFactor;
  41359. layer.plane.material.blendDst = ZeroFactor;
  41360. layer.xrlayer = this._createXRLayer( layer );
  41361. const xrlayers = this._session.renderState.layers;
  41362. xrlayers.unshift( layer.xrlayer );
  41363. this._session.updateRenderState( { layers: xrlayers } );
  41364. } else {
  41365. renderTarget.isXRRenderTarget = false;
  41366. }
  41367. return plane;
  41368. }
  41369. /**
  41370. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  41371. * rendered scene.
  41372. *
  41373. * @param {number} radius - The radius of the cylinder in world units.
  41374. * @param {number} centralAngle - The central angle of the cylinder in radians.
  41375. * @param {number} aspectratio - The aspect ratio.
  41376. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  41377. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  41378. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  41379. * @param {number} pixelheight - The height of the layer's render target in pixels.
  41380. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  41381. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  41382. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  41383. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  41384. */
  41385. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  41386. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  41387. const renderTarget = new XRRenderTarget(
  41388. pixelwidth,
  41389. pixelheight,
  41390. {
  41391. format: RGBAFormat,
  41392. type: UnsignedByteType,
  41393. depthTexture: new DepthTexture(
  41394. pixelwidth,
  41395. pixelheight,
  41396. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  41397. undefined,
  41398. undefined,
  41399. undefined,
  41400. undefined,
  41401. undefined,
  41402. undefined,
  41403. attributes.stencil ? DepthStencilFormat : DepthFormat
  41404. ),
  41405. stencilBuffer: attributes.stencil,
  41406. resolveDepthBuffer: false,
  41407. resolveStencilBuffer: false
  41408. } );
  41409. renderTarget._autoAllocateDepthBuffer = true;
  41410. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  41411. material.map = renderTarget.texture;
  41412. material.map.offset.y = 1;
  41413. material.map.repeat.y = -1;
  41414. const plane = new Mesh( geometry, material );
  41415. plane.position.copy( translation );
  41416. plane.quaternion.copy( quaternion );
  41417. const layer = {
  41418. type: 'cylinder',
  41419. radius: radius,
  41420. centralAngle: centralAngle,
  41421. aspectratio: aspectratio,
  41422. translation: translation,
  41423. quaternion: quaternion,
  41424. pixelwidth: pixelwidth,
  41425. pixelheight: pixelheight,
  41426. plane: plane,
  41427. material: material,
  41428. rendercall: rendercall,
  41429. renderTarget: renderTarget };
  41430. this._layers.push( layer );
  41431. if ( this._session !== null ) {
  41432. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  41433. layer.plane.material.blending = CustomBlending;
  41434. layer.plane.material.blendEquation = AddEquation;
  41435. layer.plane.material.blendSrc = ZeroFactor;
  41436. layer.plane.material.blendDst = ZeroFactor;
  41437. layer.xrlayer = this._createXRLayer( layer );
  41438. const xrlayers = this._session.renderState.layers;
  41439. xrlayers.unshift( layer.xrlayer );
  41440. this._session.updateRenderState( { layers: xrlayers } );
  41441. } else {
  41442. renderTarget.isXRRenderTarget = false;
  41443. }
  41444. return plane;
  41445. }
  41446. /**
  41447. * Renders the XR layers that have been previously added to the scene.
  41448. *
  41449. * This method is usually called in your animation loop before rendering
  41450. * the actual scene via `renderer.render( scene, camera );`.
  41451. */
  41452. renderLayers( ) {
  41453. const translationObject = new Vector3();
  41454. const quaternionObject = new Quaternion();
  41455. const renderer = this._renderer;
  41456. const wasPresenting = this.isPresenting;
  41457. this.isPresenting = false;
  41458. const rendererSize = new Vector2();
  41459. renderer.getSize( rendererSize );
  41460. const currentRenderTarget = renderer.getRenderTarget();
  41461. for ( const layer of this._layers ) {
  41462. layer.renderTarget.isXRRenderTarget = this._session !== null;
  41463. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  41464. const currentContextNode = renderer.contextNode;
  41465. let contextNode;
  41466. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  41467. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  41468. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  41469. renderer.backend.setXRRenderTargetTextures(
  41470. layer.renderTarget,
  41471. glSubImage.colorTexture,
  41472. undefined );
  41473. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  41474. contextNode = _contextNodeLib.get( currentContextNode );
  41475. if ( contextNode === undefined ) {
  41476. // Apply ToneMapping and OutputColorSpace directly in the material shader
  41477. contextNode = currentContextNode.context( {
  41478. getOutput: ( outputNode ) => {
  41479. return renderOutput( outputNode, renderer.toneMapping, renderer.outputColorSpace );
  41480. }
  41481. } );
  41482. _contextNodeLib.set( currentContextNode, contextNode );
  41483. }
  41484. } else {
  41485. contextNode = currentContextNode;
  41486. }
  41487. renderer.contextNode = contextNode;
  41488. renderer.setRenderTarget( layer.renderTarget );
  41489. layer.rendercall();
  41490. renderer.contextNode = currentContextNode;
  41491. }
  41492. renderer.setRenderTarget( currentRenderTarget );
  41493. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  41494. this.isPresenting = wasPresenting;
  41495. }
  41496. /**
  41497. * Returns the current XR session.
  41498. *
  41499. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  41500. */
  41501. getSession() {
  41502. return this._session;
  41503. }
  41504. /**
  41505. * After a XR session has been requested usually with one of the `*Button` modules, it
  41506. * is injected into the renderer with this method. This method triggers the start of
  41507. * the actual XR rendering.
  41508. *
  41509. * @async
  41510. * @param {XRSession} session - The XR session to set.
  41511. * @return {Promise} A Promise that resolves when the session has been set.
  41512. */
  41513. async setSession( session ) {
  41514. const renderer = this._renderer;
  41515. if ( renderer.initialized === false ) await renderer.init();
  41516. this._gl = renderer.getContext();
  41517. const gl = this._gl;
  41518. this._session = session;
  41519. if ( session !== null ) {
  41520. session.addEventListener( 'select', this._onSessionEvent );
  41521. session.addEventListener( 'selectstart', this._onSessionEvent );
  41522. session.addEventListener( 'selectend', this._onSessionEvent );
  41523. session.addEventListener( 'squeeze', this._onSessionEvent );
  41524. session.addEventListener( 'squeezestart', this._onSessionEvent );
  41525. session.addEventListener( 'squeezeend', this._onSessionEvent );
  41526. session.addEventListener( 'end', this._onSessionEnd );
  41527. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  41528. this._validateWebGPUSession();
  41529. this._currentPixelRatio = renderer.getPixelRatio();
  41530. renderer.getSize( this._currentSize );
  41531. this._currentAnimationContext = renderer._animation.getContext();
  41532. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  41533. renderer._animation.stop();
  41534. //
  41535. if ( this._isWebGPUSession() ) {
  41536. await this._initWebGPUSession( session );
  41537. } else if ( this._supportsLayers === true ) {
  41538. // default path using XRProjectionLayer
  41539. let depthFormat = null;
  41540. let depthType = null;
  41541. let glDepthFormat = null;
  41542. const attributes = gl.getContextAttributes();
  41543. await renderer.backend.makeXRCompatible();
  41544. this.setFoveation( this.getFoveation() );
  41545. if ( renderer.depth ) {
  41546. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  41547. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  41548. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  41549. }
  41550. const projectionlayerInit = {
  41551. colorFormat: gl.RGBA8,
  41552. depthFormat: glDepthFormat,
  41553. scaleFactor: this._framebufferScaleFactor,
  41554. clearOnAccess: false
  41555. };
  41556. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  41557. projectionlayerInit.textureType = 'texture-array';
  41558. this._useMultiview = true;
  41559. }
  41560. this._glBinding = this.getBinding();
  41561. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  41562. const layersArray = [ glProjLayer ];
  41563. this._glProjLayer = glProjLayer;
  41564. renderer.setPixelRatio( 1 );
  41565. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  41566. const depth = this._useMultiview ? 2 : 1;
  41567. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  41568. this._xrRenderTarget = new XRRenderTarget(
  41569. glProjLayer.textureWidth,
  41570. glProjLayer.textureHeight,
  41571. {
  41572. format: RGBAFormat,
  41573. type: UnsignedByteType,
  41574. colorSpace: renderer.outputColorSpace,
  41575. depthTexture: depthTexture,
  41576. stencilBuffer: renderer.stencil,
  41577. samples: attributes.antialias ? 4 : 0,
  41578. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  41579. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  41580. depth: this._useMultiview ? 2 : 1,
  41581. multiview: this._useMultiview
  41582. } );
  41583. this._xrRenderTarget._hasExternalTextures = true;
  41584. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  41585. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  41586. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  41587. if ( this._sessionUsesLayers ) {
  41588. // switch layers to native
  41589. for ( const layer of this._layers ) {
  41590. // change material so it "punches" out a hole to show the XR Layer.
  41591. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  41592. layer.plane.material.blending = CustomBlending;
  41593. layer.plane.material.blendEquation = AddEquation;
  41594. layer.plane.material.blendSrc = ZeroFactor;
  41595. layer.plane.material.blendDst = ZeroFactor;
  41596. layer.xrlayer = this._createXRLayer( layer );
  41597. layersArray.unshift( layer.xrlayer );
  41598. }
  41599. }
  41600. session.updateRenderState( { layers: layersArray } );
  41601. } else {
  41602. // fallback to XRWebGLLayer
  41603. await renderer.backend.makeXRCompatible();
  41604. this.setFoveation( this.getFoveation() );
  41605. const layerInit = {
  41606. antialias: renderer.currentSamples > 0,
  41607. alpha: true,
  41608. depth: renderer.depth,
  41609. stencil: renderer.stencil,
  41610. framebufferScaleFactor: this.getFramebufferScaleFactor()
  41611. };
  41612. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  41613. this._glBaseLayer = glBaseLayer;
  41614. session.updateRenderState( { baseLayer: glBaseLayer } );
  41615. renderer.setPixelRatio( 1 );
  41616. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  41617. this._xrRenderTarget = new XRRenderTarget(
  41618. glBaseLayer.framebufferWidth,
  41619. glBaseLayer.framebufferHeight,
  41620. {
  41621. format: RGBAFormat,
  41622. type: UnsignedByteType,
  41623. colorSpace: renderer.outputColorSpace,
  41624. stencilBuffer: renderer.stencil,
  41625. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  41626. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  41627. }
  41628. );
  41629. this._xrRenderTarget._isOpaqueFramebuffer = true;
  41630. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  41631. }
  41632. //
  41633. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  41634. renderer._animation.setContext( session );
  41635. renderer._animation.start();
  41636. this.isPresenting = true;
  41637. this.dispatchEvent( { type: 'sessionstart' } );
  41638. }
  41639. }
  41640. /**
  41641. * This method is called by the renderer per frame and updates the XR camera
  41642. * and it sub cameras based on the given camera. The given camera is the "user"
  41643. * camera created on application level and used for non-XR rendering.
  41644. *
  41645. * @param {PerspectiveCamera} camera - The camera.
  41646. */
  41647. updateCamera( camera ) {
  41648. const session = this._session;
  41649. if ( session === null ) return;
  41650. const depthNear = camera.near;
  41651. const depthFar = camera.far;
  41652. const cameraXR = this._cameraXR;
  41653. const cameraL = this._cameraL;
  41654. const cameraR = this._cameraR;
  41655. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  41656. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  41657. cameraXR.isMultiViewCamera = this._useMultiview;
  41658. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  41659. // Note that the new renderState won't apply until the next frame. See #18320
  41660. session.updateRenderState( {
  41661. depthNear: cameraXR.near,
  41662. depthFar: cameraXR.far
  41663. } );
  41664. this._currentDepthNear = cameraXR.near;
  41665. this._currentDepthFar = cameraXR.far;
  41666. }
  41667. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  41668. cameraXR.layers.mask = camera.layers.mask | 0b110;
  41669. cameraL.layers.mask = cameraXR.layers.mask & -5;
  41670. cameraR.layers.mask = cameraXR.layers.mask & -3;
  41671. const parent = camera.parent;
  41672. const cameras = cameraXR.cameras;
  41673. updateCamera( cameraXR, parent );
  41674. for ( let i = 0; i < cameras.length; i ++ ) {
  41675. updateCamera( cameras[ i ], parent );
  41676. }
  41677. // update projection matrix for proper view frustum culling
  41678. if ( cameras.length === 2 ) {
  41679. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  41680. } else {
  41681. // assume single camera setup (AR)
  41682. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  41683. }
  41684. // update user camera and its children
  41685. updateUserCamera( camera, cameraXR, parent );
  41686. }
  41687. /**
  41688. * Returns a WebXR controller for the given controller index.
  41689. *
  41690. * @private
  41691. * @param {number} index - The controller index.
  41692. * @return {WebXRController} The XR controller.
  41693. */
  41694. _getController( index ) {
  41695. let controller = this._controllers[ index ];
  41696. if ( controller === undefined ) {
  41697. controller = new WebXRController();
  41698. this._controllers[ index ] = controller;
  41699. }
  41700. return controller;
  41701. }
  41702. }
  41703. /**
  41704. * Assumes 2 cameras that are parallel and share an X-axis, and that
  41705. * the cameras' projection and world matrices have already been set.
  41706. * And that near and far planes are identical for both cameras.
  41707. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  41708. *
  41709. * @param {ArrayCamera} camera - The camera to update.
  41710. * @param {PerspectiveCamera} cameraL - The left camera.
  41711. * @param {PerspectiveCamera} cameraR - The right camera.
  41712. */
  41713. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  41714. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  41715. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  41716. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  41717. const projL = cameraL.projectionMatrix.elements;
  41718. const projR = cameraR.projectionMatrix.elements;
  41719. // VR systems will have identical far and near planes, and
  41720. // most likely identical top and bottom frustum extents.
  41721. // Use the left camera for these values.
  41722. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  41723. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  41724. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  41725. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  41726. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  41727. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  41728. const left = near * leftFov;
  41729. const right = near * rightFov;
  41730. // Calculate the new camera's position offset from the
  41731. // left camera. xOffset should be roughly half `ipd`.
  41732. const zOffset = ipd / ( - leftFov + rightFov );
  41733. const xOffset = zOffset * - leftFov;
  41734. // TODO: Better way to apply this offset?
  41735. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  41736. camera.translateX( xOffset );
  41737. camera.translateZ( zOffset );
  41738. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  41739. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  41740. // Check if the projection uses an infinite far plane.
  41741. if ( projL[ 10 ] === -1 ) {
  41742. // Use the projection matrix from the left eye.
  41743. // The camera offset is sufficient to include the view volumes
  41744. // of both eyes (assuming symmetric projections).
  41745. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  41746. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  41747. } else {
  41748. // Find the union of the frustum values of the cameras and scale
  41749. // the values so that the near plane's position does not change in world space,
  41750. // although must now be relative to the new union camera.
  41751. const near2 = near + zOffset;
  41752. const far2 = far + zOffset;
  41753. const left2 = left - xOffset;
  41754. const right2 = right + ( ipd - xOffset );
  41755. const top2 = topFov * far / far2 * near2;
  41756. const bottom2 = bottomFov * far / far2 * near2;
  41757. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  41758. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  41759. }
  41760. }
  41761. /**
  41762. * Updates the world matrices for the given camera based on the parent 3D object.
  41763. *
  41764. * @inner
  41765. * @param {Camera} camera - The camera to update.
  41766. * @param {Object3D} parent - The parent 3D object.
  41767. */
  41768. function updateCamera( camera, parent ) {
  41769. if ( parent === null ) {
  41770. camera.matrixWorld.copy( camera.matrix );
  41771. } else {
  41772. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  41773. }
  41774. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  41775. }
  41776. /**
  41777. * Updates the given camera with the transformation of the XR camera and parent object.
  41778. *
  41779. * @inner
  41780. * @param {Camera} camera - The camera to update.
  41781. * @param {ArrayCamera} cameraXR - The XR camera.
  41782. * @param {Object3D} parent - The parent 3D object.
  41783. */
  41784. function updateUserCamera( camera, cameraXR, parent ) {
  41785. if ( parent === null ) {
  41786. camera.matrix.copy( cameraXR.matrixWorld );
  41787. } else {
  41788. camera.matrix.copy( parent.matrixWorld );
  41789. camera.matrix.invert();
  41790. camera.matrix.multiply( cameraXR.matrixWorld );
  41791. }
  41792. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  41793. camera.updateMatrixWorld( true );
  41794. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  41795. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  41796. if ( camera.isPerspectiveCamera ) {
  41797. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  41798. camera.zoom = 1;
  41799. }
  41800. }
  41801. function onSessionEvent( event ) {
  41802. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  41803. if ( controllerIndex === -1 ) {
  41804. return;
  41805. }
  41806. const controller = this._controllers[ controllerIndex ];
  41807. if ( controller !== undefined ) {
  41808. const referenceSpace = this.getReferenceSpace();
  41809. controller.update( event.inputSource, event.frame, referenceSpace );
  41810. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  41811. }
  41812. }
  41813. function onSessionEnd() {
  41814. const session = this._session;
  41815. const renderer = this._renderer;
  41816. session.removeEventListener( 'select', this._onSessionEvent );
  41817. session.removeEventListener( 'selectstart', this._onSessionEvent );
  41818. session.removeEventListener( 'selectend', this._onSessionEvent );
  41819. session.removeEventListener( 'squeeze', this._onSessionEvent );
  41820. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  41821. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  41822. session.removeEventListener( 'end', this._onSessionEnd );
  41823. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  41824. for ( let i = 0; i < this._controllers.length; i ++ ) {
  41825. const inputSource = this._controllerInputSources[ i ];
  41826. if ( inputSource === null ) continue;
  41827. this._controllerInputSources[ i ] = null;
  41828. this._controllers[ i ].disconnect( inputSource );
  41829. }
  41830. this._currentDepthNear = null;
  41831. this._currentDepthFar = null;
  41832. if ( this._currentSamples !== null ) {
  41833. renderer._samples = this._currentSamples;
  41834. this._currentSamples = null;
  41835. }
  41836. // restore framebuffer/rendering state
  41837. renderer._resetXRState();
  41838. this._disposeWebGPUSession();
  41839. this._session = null;
  41840. this._xrRenderTarget = null;
  41841. this._glBinding = null;
  41842. this._webgpuBinding = null;
  41843. this._glBaseLayer = null;
  41844. this._glProjLayer = null;
  41845. // switch layers back to emulated
  41846. if ( this._sessionUsesLayers === true ) {
  41847. for ( const layer of this._layers ) {
  41848. // Recreate layer render target to reset state
  41849. layer.renderTarget = new XRRenderTarget(
  41850. layer.pixelwidth,
  41851. layer.pixelheight,
  41852. {
  41853. format: RGBAFormat,
  41854. type: UnsignedByteType,
  41855. depthTexture: new DepthTexture(
  41856. layer.pixelwidth,
  41857. layer.pixelheight,
  41858. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  41859. undefined,
  41860. undefined,
  41861. undefined,
  41862. undefined,
  41863. undefined,
  41864. undefined,
  41865. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  41866. ),
  41867. stencilBuffer: layer.stencilBuffer,
  41868. resolveDepthBuffer: false,
  41869. resolveStencilBuffer: false
  41870. } );
  41871. layer.renderTarget.isXRRenderTarget = false;
  41872. layer.plane.material = layer.material;
  41873. layer.material.map = layer.renderTarget.texture;
  41874. layer.material.map.offset.y = 1;
  41875. layer.material.map.repeat.y = -1;
  41876. delete layer.xrlayer;
  41877. }
  41878. }
  41879. //
  41880. this.isPresenting = false;
  41881. this._useMultiview = false;
  41882. renderer._animation.stop();
  41883. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  41884. renderer._animation.setContext( this._currentAnimationContext );
  41885. renderer._animation.start();
  41886. renderer.setPixelRatio( this._currentPixelRatio );
  41887. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  41888. this.dispatchEvent( { type: 'sessionend' } );
  41889. }
  41890. function onInputSourcesChange( event ) {
  41891. const controllers = this._controllers;
  41892. const controllerInputSources = this._controllerInputSources;
  41893. // Notify disconnected
  41894. for ( let i = 0; i < event.removed.length; i ++ ) {
  41895. const inputSource = event.removed[ i ];
  41896. const index = controllerInputSources.indexOf( inputSource );
  41897. if ( index >= 0 ) {
  41898. controllerInputSources[ index ] = null;
  41899. controllers[ index ].disconnect( inputSource );
  41900. }
  41901. }
  41902. // Notify connected
  41903. for ( let i = 0; i < event.added.length; i ++ ) {
  41904. const inputSource = event.added[ i ];
  41905. let controllerIndex = controllerInputSources.indexOf( inputSource );
  41906. if ( controllerIndex === -1 ) {
  41907. // Assign input source a controller that currently has no input source
  41908. for ( let i = 0; i < controllers.length; i ++ ) {
  41909. if ( i >= controllerInputSources.length ) {
  41910. controllerInputSources.push( inputSource );
  41911. controllerIndex = i;
  41912. break;
  41913. } else if ( controllerInputSources[ i ] === null ) {
  41914. controllerInputSources[ i ] = inputSource;
  41915. controllerIndex = i;
  41916. break;
  41917. }
  41918. }
  41919. // If all controllers do currently receive input we ignore new ones
  41920. if ( controllerIndex === -1 ) break;
  41921. }
  41922. const controller = controllers[ controllerIndex ];
  41923. if ( controller ) {
  41924. controller.connect( inputSource );
  41925. }
  41926. }
  41927. }
  41928. // Creation method for native WebXR layers
  41929. function createXRLayer( layer ) {
  41930. if ( layer.type === 'quad' ) {
  41931. return this._glBinding.createQuadLayer( {
  41932. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  41933. width: layer.width / 2,
  41934. height: layer.height / 2,
  41935. space: this._referenceSpace,
  41936. viewPixelWidth: layer.pixelwidth,
  41937. viewPixelHeight: layer.pixelheight,
  41938. clearOnAccess: false
  41939. } );
  41940. } else {
  41941. return this._glBinding.createCylinderLayer( {
  41942. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  41943. radius: layer.radius,
  41944. centralAngle: layer.centralAngle,
  41945. aspectRatio: layer.aspectRatio,
  41946. space: this._referenceSpace,
  41947. viewPixelWidth: layer.pixelwidth,
  41948. viewPixelHeight: layer.pixelheight,
  41949. clearOnAccess: false
  41950. } );
  41951. }
  41952. }
  41953. // Animation Loop
  41954. function onAnimationFrame( time, frame ) {
  41955. if ( frame === undefined ) return;
  41956. const cameraXR = this._cameraXR;
  41957. const renderer = this._renderer;
  41958. const backend = renderer.backend;
  41959. const glBaseLayer = this._glBaseLayer;
  41960. const referenceSpace = this.getReferenceSpace();
  41961. const pose = frame.getViewerPose( referenceSpace );
  41962. this._xrFrame = frame;
  41963. if ( pose !== null ) {
  41964. const views = pose.views;
  41965. const webgpuViewData = this._isWebGPUSession() ? this._getWebGPUViewData( views ) : null;
  41966. if ( this._glBaseLayer !== null && webgpuViewData === null ) {
  41967. backend.setXRTarget( glBaseLayer.framebuffer );
  41968. }
  41969. let cameraXRNeedsUpdate = false;
  41970. // check if it's necessary to rebuild cameraXR's camera list
  41971. if ( views.length !== cameraXR.cameras.length ) {
  41972. cameraXR.cameras.length = 0;
  41973. cameraXRNeedsUpdate = true;
  41974. }
  41975. for ( let i = 0; i < views.length; i ++ ) {
  41976. const view = views[ i ];
  41977. let viewport;
  41978. if ( webgpuViewData !== null ) {
  41979. viewport = webgpuViewData.viewports[ i ];
  41980. } else if ( this._supportsLayers === true ) {
  41981. // WebGL path: Use XRWebGLBinding
  41982. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  41983. viewport = glSubImage.viewport;
  41984. // For side-by-side projection, we only produce a single texture for both eyes.
  41985. if ( i === 0 ) {
  41986. backend.setXRRenderTargetTextures(
  41987. this._xrRenderTarget,
  41988. glSubImage.colorTexture,
  41989. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  41990. );
  41991. }
  41992. } else {
  41993. viewport = glBaseLayer.getViewport( view );
  41994. }
  41995. let camera = this._cameras[ i ];
  41996. if ( camera === undefined ) {
  41997. camera = new PerspectiveCamera();
  41998. camera.layers.enable( i );
  41999. camera.viewport = new Vector4();
  42000. camera.matrixWorldAutoUpdate = false;
  42001. this._cameras[ i ] = camera;
  42002. }
  42003. camera.matrix.fromArray( view.transform.matrix );
  42004. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  42005. camera.projectionMatrix.fromArray( view.projectionMatrix );
  42006. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  42007. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  42008. if ( i === 0 ) {
  42009. cameraXR.matrix.copy( camera.matrix );
  42010. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  42011. }
  42012. if ( cameraXRNeedsUpdate === true ) {
  42013. cameraXR.cameras.push( camera );
  42014. }
  42015. }
  42016. if ( webgpuViewData !== null && webgpuViewData.colorTexture !== null ) {
  42017. backend.setXRRenderTargetTextures(
  42018. this._xrRenderTarget,
  42019. webgpuViewData.colorTexture,
  42020. webgpuViewData.viewDescriptors
  42021. );
  42022. }
  42023. renderer.setOutputRenderTarget( this._xrRenderTarget );
  42024. const frameBufferTarget = renderer._getFrameBufferTarget();
  42025. renderer.xr.foveateBoundTexture( frameBufferTarget );
  42026. }
  42027. //
  42028. for ( let i = 0; i < this._controllers.length; i ++ ) {
  42029. const inputSource = this._controllerInputSources[ i ];
  42030. const controller = this._controllers[ i ];
  42031. if ( inputSource !== null && controller !== undefined ) {
  42032. controller.update( inputSource, frame, referenceSpace );
  42033. }
  42034. }
  42035. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  42036. if ( frame.detectedPlanes ) {
  42037. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  42038. }
  42039. this._xrFrame = null;
  42040. }
  42041. /**
  42042. * CanvasTarget is a class that represents the final output destination of the renderer.
  42043. *
  42044. * @augments EventDispatcher
  42045. */
  42046. class CanvasTarget extends EventDispatcher {
  42047. /**
  42048. * Constructs a new CanvasTarget.
  42049. *
  42050. * @param {HTMLCanvasElement|OffscreenCanvas} domElement - The canvas element to render to.
  42051. */
  42052. constructor( domElement ) {
  42053. super();
  42054. /**
  42055. * A reference to the canvas element the renderer is drawing to.
  42056. * This value of this property will automatically be created by
  42057. * the renderer.
  42058. *
  42059. * @type {HTMLCanvasElement|OffscreenCanvas}
  42060. */
  42061. this.domElement = domElement;
  42062. /**
  42063. * The renderer's pixel ratio.
  42064. *
  42065. * @private
  42066. * @type {number}
  42067. * @default 1
  42068. */
  42069. this._pixelRatio = 1;
  42070. /**
  42071. * The width of the renderer's default framebuffer in logical pixel unit.
  42072. *
  42073. * @private
  42074. * @type {number}
  42075. */
  42076. this._width = this.domElement.width;
  42077. /**
  42078. * The height of the renderer's default framebuffer in logical pixel unit.
  42079. *
  42080. * @private
  42081. * @type {number}
  42082. */
  42083. this._height = this.domElement.height;
  42084. /**
  42085. * The viewport of the renderer in logical pixel unit.
  42086. *
  42087. * @private
  42088. * @type {Vector4}
  42089. */
  42090. this._viewport = new Vector4( 0, 0, this._width, this._height );
  42091. /**
  42092. * The scissor rectangle of the renderer in logical pixel unit.
  42093. *
  42094. * @private
  42095. * @type {Vector4}
  42096. */
  42097. this._scissor = new Vector4( 0, 0, this._width, this._height );
  42098. /**
  42099. * Whether the scissor test should be enabled or not.
  42100. *
  42101. * @private
  42102. * @type {boolean}
  42103. */
  42104. this._scissorTest = false;
  42105. /**
  42106. * The color texture of the default framebuffer.
  42107. *
  42108. * @type {FramebufferTexture}
  42109. */
  42110. this.colorTexture = new FramebufferTexture();
  42111. /**
  42112. * The depth texture of the default framebuffer.
  42113. *
  42114. * @type {DepthTexture}
  42115. */
  42116. this.depthTexture = new DepthTexture();
  42117. }
  42118. /**
  42119. * Returns the pixel ratio.
  42120. *
  42121. * @return {number} The pixel ratio.
  42122. */
  42123. getPixelRatio() {
  42124. return this._pixelRatio;
  42125. }
  42126. /**
  42127. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  42128. *
  42129. * @param {Vector2} target - The method writes the result in this target object.
  42130. * @return {Vector2} The drawing buffer size.
  42131. */
  42132. getDrawingBufferSize( target ) {
  42133. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  42134. }
  42135. /**
  42136. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  42137. *
  42138. * @param {Vector2} target - The method writes the result in this target object.
  42139. * @return {Vector2} The renderer's size in logical pixels.
  42140. */
  42141. getSize( target ) {
  42142. return target.set( this._width, this._height );
  42143. }
  42144. /**
  42145. * Sets the given pixel ratio and resizes the canvas if necessary.
  42146. *
  42147. * @param {number} [value=1] - The pixel ratio.
  42148. */
  42149. setPixelRatio( value = 1 ) {
  42150. if ( this._pixelRatio === value ) return;
  42151. this._pixelRatio = value;
  42152. this.setSize( this._width, this._height, false );
  42153. }
  42154. /**
  42155. * This method allows to define the drawing buffer size by specifying
  42156. * width, height and pixel ratio all at once. The size of the drawing
  42157. * buffer is computed with this formula:
  42158. * ```js
  42159. * size.x = width * pixelRatio;
  42160. * size.y = height * pixelRatio;
  42161. * ```
  42162. *
  42163. * @param {number} width - The width in logical pixels.
  42164. * @param {number} height - The height in logical pixels.
  42165. * @param {number} pixelRatio - The pixel ratio.
  42166. */
  42167. setDrawingBufferSize( width, height, pixelRatio ) {
  42168. // Renderer can't be resized while presenting in XR.
  42169. if ( this.xr && this.xr.isPresenting ) return;
  42170. this._width = width;
  42171. this._height = height;
  42172. this._pixelRatio = pixelRatio;
  42173. this.domElement.width = Math.floor( width * pixelRatio );
  42174. this.domElement.height = Math.floor( height * pixelRatio );
  42175. this.setViewport( 0, 0, width, height );
  42176. this._dispatchResize();
  42177. }
  42178. /**
  42179. * Sets the size of the renderer.
  42180. *
  42181. * @param {number} width - The width in logical pixels.
  42182. * @param {number} height - The height in logical pixels.
  42183. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  42184. */
  42185. setSize( width, height, updateStyle = true ) {
  42186. // Renderer can't be resized while presenting in XR.
  42187. if ( this.xr && this.xr.isPresenting ) return;
  42188. this._width = width;
  42189. this._height = height;
  42190. this.domElement.width = Math.floor( width * this._pixelRatio );
  42191. this.domElement.height = Math.floor( height * this._pixelRatio );
  42192. if ( updateStyle === true ) {
  42193. this.domElement.style.width = width + 'px';
  42194. this.domElement.style.height = height + 'px';
  42195. }
  42196. this.setViewport( 0, 0, width, height );
  42197. this._dispatchResize();
  42198. }
  42199. /**
  42200. * Returns the scissor rectangle.
  42201. *
  42202. * @param {Vector4} target - The method writes the result in this target object.
  42203. * @return {Vector4} The scissor rectangle.
  42204. */
  42205. getScissor( target ) {
  42206. const scissor = this._scissor;
  42207. target.x = scissor.x;
  42208. target.y = scissor.y;
  42209. target.width = scissor.width;
  42210. target.height = scissor.height;
  42211. return target;
  42212. }
  42213. /**
  42214. * Defines the scissor rectangle.
  42215. *
  42216. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  42217. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  42218. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  42219. * @param {number} width - The width of the scissor box in logical pixel unit.
  42220. * @param {number} height - The height of the scissor box in logical pixel unit.
  42221. */
  42222. setScissor( x, y, width, height ) {
  42223. const scissor = this._scissor;
  42224. if ( x.isVector4 ) {
  42225. scissor.copy( x );
  42226. } else {
  42227. scissor.set( x, y, width, height );
  42228. }
  42229. }
  42230. /**
  42231. * Returns the scissor test value.
  42232. *
  42233. * @return {boolean} Whether the scissor test should be enabled or not.
  42234. */
  42235. getScissorTest() {
  42236. return this._scissorTest;
  42237. }
  42238. /**
  42239. * Defines the scissor test.
  42240. *
  42241. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  42242. */
  42243. setScissorTest( boolean ) {
  42244. this._scissorTest = boolean;
  42245. }
  42246. /**
  42247. * Returns the viewport definition.
  42248. *
  42249. * @param {Vector4} target - The method writes the result in this target object.
  42250. * @return {Vector4} The viewport definition.
  42251. */
  42252. getViewport( target ) {
  42253. return target.copy( this._viewport );
  42254. }
  42255. /**
  42256. * Defines the viewport.
  42257. *
  42258. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  42259. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  42260. * @param {number} width - The width of the viewport in logical pixel unit.
  42261. * @param {number} height - The height of the viewport in logical pixel unit.
  42262. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  42263. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  42264. */
  42265. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  42266. const viewport = this._viewport;
  42267. if ( x.isVector4 ) {
  42268. viewport.copy( x );
  42269. } else {
  42270. viewport.set( x, y, width, height );
  42271. }
  42272. viewport.minDepth = minDepth;
  42273. viewport.maxDepth = maxDepth;
  42274. }
  42275. /**
  42276. * Dispatches the resize event.
  42277. *
  42278. * @private
  42279. */
  42280. _dispatchResize() {
  42281. this.dispatchEvent( { type: 'resize' } );
  42282. }
  42283. /**
  42284. * Frees the GPU-related resources allocated by this instance. Call this
  42285. * method whenever this instance is no longer used in your app.
  42286. *
  42287. * @fires RenderTarget#dispose
  42288. */
  42289. dispose() {
  42290. this.dispatchEvent( { type: 'dispose' } );
  42291. }
  42292. }
  42293. const _scene = /*@__PURE__*/ new Scene();
  42294. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  42295. const _screen = /*@__PURE__*/ new Vector4();
  42296. const _frustum = /*@__PURE__*/ new Frustum();
  42297. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  42298. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  42299. const _vector4 = /*@__PURE__*/ new Vector4();
  42300. const _shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  42301. /**
  42302. * Base class for renderers.
  42303. */
  42304. class Renderer {
  42305. /**
  42306. * Renderer options.
  42307. *
  42308. * @typedef {Object} Renderer~Options
  42309. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  42310. * @property {boolean} [reversedDepthBuffer=false] - Whether reversed depth buffer is enabled or not.
  42311. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  42312. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  42313. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  42314. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  42315. * @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
  42316. * to overwrite the default.
  42317. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  42318. * @property {number} [outputBufferType=HalfFloatType] - Defines the type of output buffers. The default `HalfFloatType` is recommend for best
  42319. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  42320. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  42321. */
  42322. /**
  42323. * Constructs a new renderer.
  42324. *
  42325. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  42326. * @param {Renderer~Options} [parameters] - The configuration parameter.
  42327. */
  42328. constructor( backend, parameters = {} ) {
  42329. /**
  42330. * This flag can be used for type testing.
  42331. *
  42332. * @type {boolean}
  42333. * @readonly
  42334. * @default true
  42335. */
  42336. this.isRenderer = true;
  42337. //
  42338. const {
  42339. logarithmicDepthBuffer = false,
  42340. reversedDepthBuffer = false,
  42341. alpha = true,
  42342. depth = true,
  42343. stencil = false,
  42344. antialias = false,
  42345. samples = 0,
  42346. getFallback = null,
  42347. outputBufferType = HalfFloatType,
  42348. multiview = false
  42349. } = parameters;
  42350. /**
  42351. * A reference to the current backend.
  42352. *
  42353. * @type {Backend}
  42354. */
  42355. this.backend = backend;
  42356. /**
  42357. * Whether the renderer should automatically clear the current rendering target
  42358. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  42359. * or the current bound render target (custom framebuffer).
  42360. *
  42361. * @type {boolean}
  42362. * @default true
  42363. */
  42364. this.autoClear = true;
  42365. /**
  42366. * When `autoClear` is set to `true`, this property defines whether the renderer
  42367. * should clear the color buffer.
  42368. *
  42369. * @type {boolean}
  42370. * @default true
  42371. */
  42372. this.autoClearColor = true;
  42373. /**
  42374. * When `autoClear` is set to `true`, this property defines whether the renderer
  42375. * should clear the depth buffer.
  42376. *
  42377. * @type {boolean}
  42378. * @default true
  42379. */
  42380. this.autoClearDepth = true;
  42381. /**
  42382. * When `autoClear` is set to `true`, this property defines whether the renderer
  42383. * should clear the stencil buffer.
  42384. *
  42385. * @type {boolean}
  42386. * @default true
  42387. */
  42388. this.autoClearStencil = true;
  42389. /**
  42390. * Whether the default framebuffer should be transparent or opaque.
  42391. *
  42392. * @type {boolean}
  42393. * @default true
  42394. */
  42395. this.alpha = alpha;
  42396. /**
  42397. * Whether logarithmic depth buffer is enabled or not.
  42398. *
  42399. * @type {boolean}
  42400. * @default false
  42401. * @readonly
  42402. */
  42403. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  42404. /**
  42405. * Whether reversed depth buffer is enabled or not.
  42406. *
  42407. * @type {boolean}
  42408. * @default false
  42409. * @readonly
  42410. */
  42411. this.reversedDepthBuffer = reversedDepthBuffer;
  42412. /**
  42413. * Defines the output color space of the renderer.
  42414. *
  42415. * @type {string}
  42416. * @default SRGBColorSpace
  42417. */
  42418. this.outputColorSpace = SRGBColorSpace;
  42419. /**
  42420. * Defines the tone mapping of the renderer.
  42421. *
  42422. * @type {number}
  42423. * @default NoToneMapping
  42424. */
  42425. this.toneMapping = NoToneMapping;
  42426. /**
  42427. * Defines the tone mapping exposure.
  42428. *
  42429. * @type {number}
  42430. * @default 1
  42431. */
  42432. this.toneMappingExposure = 1.0;
  42433. /**
  42434. * Whether the renderer should sort its render lists or not.
  42435. *
  42436. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  42437. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  42438. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  42439. * e.g. manually determining each object's rendering order.
  42440. *
  42441. * @type {boolean}
  42442. * @default true
  42443. */
  42444. this.sortObjects = true;
  42445. /**
  42446. * Whether the default framebuffer should have a depth buffer or not.
  42447. *
  42448. * @type {boolean}
  42449. * @default true
  42450. */
  42451. this.depth = depth;
  42452. /**
  42453. * Whether the default framebuffer should have a stencil buffer or not.
  42454. *
  42455. * @type {boolean}
  42456. * @default false
  42457. */
  42458. this.stencil = stencil;
  42459. /**
  42460. * Holds a series of statistical information about the GPU memory
  42461. * and the rendering process. Useful for debugging and monitoring.
  42462. *
  42463. * @type {Info}
  42464. */
  42465. this.info = new Info();
  42466. /**
  42467. * A global context node that stores override nodes for specific transformations or calculations.
  42468. * These nodes can be used to replace default behavior in the rendering pipeline.
  42469. *
  42470. * @type {ContextNode}
  42471. * @property {Object} value - The context value object.
  42472. */
  42473. this.contextNode = context();
  42474. /**
  42475. * The node library defines how certain library objects like materials, lights
  42476. * or tone mapping functions are mapped to node types. This is required since
  42477. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  42478. * be part of the scene graph, they are internally represented as nodes for
  42479. * further processing.
  42480. *
  42481. * @type {NodeLibrary}
  42482. */
  42483. this.library = new NodeLibrary();
  42484. /**
  42485. * A map-like data structure for managing lights.
  42486. *
  42487. * @type {Lighting}
  42488. */
  42489. this.lighting = new Lighting();
  42490. // internals
  42491. /**
  42492. * The number of MSAA samples.
  42493. *
  42494. * @private
  42495. * @type {number}
  42496. * @default 0
  42497. */
  42498. this._samples = samples || ( antialias === true ) ? 4 : 0;
  42499. /**
  42500. * OnCanvasTargetResize callback function.
  42501. *
  42502. * @private
  42503. * @type {Function}
  42504. */
  42505. this._onCanvasTargetResize = this._onCanvasTargetResize.bind( this );
  42506. /**
  42507. * The canvas target for rendering.
  42508. *
  42509. * @private
  42510. * @type {CanvasTarget}
  42511. */
  42512. this._canvasTarget = new CanvasTarget( backend.getDomElement() );
  42513. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  42514. this._canvasTarget.isDefaultCanvasTarget = true;
  42515. /**
  42516. * The inspector provides information about the internal renderer state.
  42517. *
  42518. * @private
  42519. * @type {InspectorBase}
  42520. */
  42521. this._inspector = new InspectorBase();
  42522. this._inspector.setRenderer( this );
  42523. /**
  42524. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  42525. *
  42526. * @private
  42527. * @type {?Function}
  42528. */
  42529. this._getFallback = getFallback;
  42530. /**
  42531. * A reference to a renderer module for managing shader attributes.
  42532. *
  42533. * @private
  42534. * @type {?Attributes}
  42535. * @default null
  42536. */
  42537. this._attributes = null;
  42538. /**
  42539. * A reference to a renderer module for managing geometries.
  42540. *
  42541. * @private
  42542. * @type {?Geometries}
  42543. * @default null
  42544. */
  42545. this._geometries = null;
  42546. /**
  42547. * A reference to a renderer module for managing node related logic.
  42548. *
  42549. * @private
  42550. * @type {?NodeManager}
  42551. * @default null
  42552. */
  42553. this._nodes = null;
  42554. /**
  42555. * A reference to a renderer module for managing the internal animation loop.
  42556. *
  42557. * @private
  42558. * @type {?Animation}
  42559. * @default null
  42560. */
  42561. this._animation = null;
  42562. /**
  42563. * A reference to a renderer module for managing shader program bindings.
  42564. *
  42565. * @private
  42566. * @type {?Bindings}
  42567. * @default null
  42568. */
  42569. this._bindings = null;
  42570. /**
  42571. * A reference to a renderer module for managing render objects.
  42572. *
  42573. * @private
  42574. * @type {?RenderObjects}
  42575. * @default null
  42576. */
  42577. this._objects = null;
  42578. /**
  42579. * A reference to a renderer module for managing render and compute pipelines.
  42580. *
  42581. * @private
  42582. * @type {?Pipelines}
  42583. * @default null
  42584. */
  42585. this._pipelines = null;
  42586. /**
  42587. * A reference to a renderer module for managing render bundles.
  42588. *
  42589. * @private
  42590. * @type {?RenderBundles}
  42591. * @default null
  42592. */
  42593. this._bundles = null;
  42594. /**
  42595. * A reference to a renderer module for managing render lists.
  42596. *
  42597. * @private
  42598. * @type {?RenderLists}
  42599. * @default null
  42600. */
  42601. this._renderLists = null;
  42602. /**
  42603. * A reference to a renderer module for managing render contexts.
  42604. *
  42605. * @private
  42606. * @type {?RenderContexts}
  42607. * @default null
  42608. */
  42609. this._renderContexts = null;
  42610. /**
  42611. * A reference to a renderer module for managing textures.
  42612. *
  42613. * @private
  42614. * @type {?Textures}
  42615. * @default null
  42616. */
  42617. this._textures = null;
  42618. /**
  42619. * A reference to a renderer module for backgrounds.
  42620. *
  42621. * @private
  42622. * @type {?Background}
  42623. * @default null
  42624. */
  42625. this._background = null;
  42626. /**
  42627. * Cache for the fullscreen quad.
  42628. * This fullscreen quad is used for internal render passes
  42629. * like the tone mapping and color space output pass.
  42630. *
  42631. * @private
  42632. * @type {Map<Texture,QuadMesh>}
  42633. */
  42634. this._quadCache = new Map();
  42635. /**
  42636. * A reference to the current render context.
  42637. *
  42638. * @private
  42639. * @type {?RenderContext}
  42640. * @default null
  42641. */
  42642. this._currentRenderContext = null;
  42643. /**
  42644. * A custom sort function for the opaque render list.
  42645. *
  42646. * @private
  42647. * @type {?Function}
  42648. * @default null
  42649. */
  42650. this._opaqueSort = null;
  42651. /**
  42652. * A custom sort function for the transparent render list.
  42653. *
  42654. * @private
  42655. * @type {?Function}
  42656. * @default null
  42657. */
  42658. this._transparentSort = null;
  42659. /**
  42660. * Cache of framebuffer targets per canvas target.
  42661. *
  42662. * @private
  42663. * @type {Map<CanvasTarget, RenderTarget>}
  42664. */
  42665. this._frameBufferTargets = new Map();
  42666. const alphaClear = this.alpha === true ? 0 : 1;
  42667. /**
  42668. * The clear color value.
  42669. *
  42670. * @private
  42671. * @type {Color4}
  42672. */
  42673. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  42674. /**
  42675. * The clear depth value.
  42676. *
  42677. * @private
  42678. * @type {number}
  42679. * @default 1
  42680. */
  42681. this._clearDepth = 1;
  42682. /**
  42683. * The clear stencil value.
  42684. *
  42685. * @private
  42686. * @type {number}
  42687. * @default 0
  42688. */
  42689. this._clearStencil = 0;
  42690. /**
  42691. * The current render target.
  42692. *
  42693. * @private
  42694. * @type {?RenderTarget}
  42695. * @default null
  42696. */
  42697. this._renderTarget = null;
  42698. /**
  42699. * The active cube face.
  42700. *
  42701. * @private
  42702. * @type {number}
  42703. * @default 0
  42704. */
  42705. this._activeCubeFace = 0;
  42706. /**
  42707. * The active mipmap level.
  42708. *
  42709. * @private
  42710. * @type {number}
  42711. * @default 0
  42712. */
  42713. this._activeMipmapLevel = 0;
  42714. /**
  42715. * The current output render target.
  42716. *
  42717. * @private
  42718. * @type {?RenderTarget}
  42719. * @default null
  42720. */
  42721. this._outputRenderTarget = null;
  42722. /**
  42723. * The MRT setting.
  42724. *
  42725. * @private
  42726. * @type {?MRTNode}
  42727. * @default null
  42728. */
  42729. this._mrt = null;
  42730. /**
  42731. * This function defines how a render object is going
  42732. * to be rendered.
  42733. *
  42734. * @private
  42735. * @type {?Function}
  42736. * @default null
  42737. */
  42738. this._renderObjectFunction = null;
  42739. /**
  42740. * Used to keep track of the current render object function.
  42741. *
  42742. * @private
  42743. * @type {?Function}
  42744. * @default null
  42745. */
  42746. this._currentRenderObjectFunction = null;
  42747. /**
  42748. * Used to keep track of the current render bundle.
  42749. *
  42750. * @private
  42751. * @type {?RenderBundle}
  42752. * @default null
  42753. */
  42754. this._currentRenderBundle = null;
  42755. /**
  42756. * Next to `_renderObjectFunction()`, this function provides another hook
  42757. * for influencing the render process of a render object. It is meant for internal
  42758. * use and only relevant for `compileAsync()` right now. Instead of using
  42759. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  42760. * a different function might be used which performs no draw but just the node
  42761. * and pipeline updates.
  42762. *
  42763. * @private
  42764. * @type {Function}
  42765. */
  42766. this._handleObjectFunction = this._renderObjectDirect;
  42767. /**
  42768. * Indicates whether the device has been lost or not. In WebGL terms, the device
  42769. * lost is considered as a context lost. When this is set to `true`, rendering
  42770. * isn't possible anymore.
  42771. *
  42772. * @private
  42773. * @type {boolean}
  42774. * @default false
  42775. */
  42776. this._isDeviceLost = false;
  42777. /**
  42778. * A callback function that defines what should happen when a device/context lost occurs.
  42779. *
  42780. * @type {Function}
  42781. */
  42782. this.onDeviceLost = this._onDeviceLost;
  42783. /**
  42784. * A callback function that defines what should happen when an uncaptured
  42785. * backend error is reported (e.g. a WebGPU validation/out-of-memory/internal
  42786. * error raised outside an error scope). Applications can override this to
  42787. * surface errors in their own UI without letting them escalate to a device
  42788. * loss. The default implementation logs to the console.
  42789. *
  42790. * @type {Function}
  42791. */
  42792. this.onError = this._onError;
  42793. /**
  42794. * Defines the type of output buffers. The default `HalfFloatType` is recommend for
  42795. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  42796. * This will reduce rendering quality though.
  42797. *
  42798. * @private
  42799. * @type {number}
  42800. * @default HalfFloatType
  42801. */
  42802. this._outputBufferType = outputBufferType;
  42803. /**
  42804. * A cache for shadow nodes per material
  42805. *
  42806. * @private
  42807. * @type {WeakMap<Material, Object>}
  42808. */
  42809. this._cacheShadowNodes = new WeakMap();
  42810. /**
  42811. * Whether the renderer has been initialized or not.
  42812. *
  42813. * @private
  42814. * @type {boolean}
  42815. * @default false
  42816. */
  42817. this._initialized = false;
  42818. /**
  42819. * The call depth of the renderer. Counts the number of
  42820. * nested render calls.
  42821. *
  42822. * @private
  42823. * @type {number}
  42824. * @default - 1
  42825. */
  42826. this._callDepth = -1;
  42827. /**
  42828. * A reference to the promise which initializes the renderer.
  42829. *
  42830. * @private
  42831. * @type {?Promise<this>}
  42832. * @default null
  42833. */
  42834. this._initPromise = null;
  42835. /**
  42836. * An array of compilation promises which are used in `compileAsync()`.
  42837. *
  42838. * @private
  42839. * @type {?Array<Promise>}
  42840. * @default null
  42841. */
  42842. this._compilationPromises = null;
  42843. /**
  42844. * When an override material is in use, this property points to the current
  42845. * source material during the rendering of a render object.
  42846. *
  42847. * @private
  42848. * @type {?Material}
  42849. * @default null
  42850. */
  42851. this._currentSourceMaterial = null;
  42852. /**
  42853. * Whether the renderer should render transparent render objects or not.
  42854. *
  42855. * @type {boolean}
  42856. * @default true
  42857. */
  42858. this.transparent = true;
  42859. /**
  42860. * Whether the renderer should render opaque render objects or not.
  42861. *
  42862. * @type {boolean}
  42863. * @default true
  42864. */
  42865. this.opaque = true;
  42866. /**
  42867. * Shadow map configuration
  42868. * @typedef {Object} ShadowMapConfig
  42869. * @property {boolean} enabled - Whether to globally enable shadows or not.
  42870. * @property {boolean} transmitted - Whether to enable light transmission through non-opaque materials.
  42871. * @property {number} type - The shadow map type.
  42872. */
  42873. /**
  42874. * The renderer's shadow configuration.
  42875. *
  42876. * @type {ShadowMapConfig}
  42877. */
  42878. this.shadowMap = {
  42879. enabled: false,
  42880. transmitted: false,
  42881. type: PCFShadowMap
  42882. };
  42883. /**
  42884. * XR configuration.
  42885. * @typedef {Object} XRConfig
  42886. * @property {boolean} enabled - Whether to globally enable XR or not.
  42887. */
  42888. /**
  42889. * The renderer's XR manager.
  42890. *
  42891. * @type {XRManager}
  42892. */
  42893. this.xr = new XRManager( this, multiview );
  42894. /**
  42895. * Debug configuration.
  42896. * @typedef {Object} DebugConfig
  42897. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  42898. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  42899. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  42900. */
  42901. /**
  42902. * The renderer's debug configuration.
  42903. *
  42904. * @type {DebugConfig}
  42905. */
  42906. this.debug = {
  42907. checkShaderErrors: true,
  42908. onShaderError: null,
  42909. getShaderAsync: async ( scene, camera, object ) => {
  42910. await this.compileAsync( object, camera, scene );
  42911. const useFrameBufferTarget = this.needsFrameBufferTarget && this._renderTarget === null;
  42912. const renderTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : ( this._renderTarget || this._outputRenderTarget );
  42913. const renderList = this._renderLists.get( scene, camera );
  42914. const renderContext = this._renderContexts.get( renderTarget, this._mrt );
  42915. const material = scene.overrideMaterial || object.material;
  42916. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  42917. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  42918. return { fragmentShader, vertexShader };
  42919. }
  42920. };
  42921. }
  42922. /**
  42923. * Initializes the renderer so it is ready for usage.
  42924. *
  42925. * @async
  42926. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  42927. */
  42928. async init() {
  42929. if ( this._initPromise !== null ) {
  42930. return this._initPromise;
  42931. }
  42932. this._initPromise = new Promise( async ( resolve, reject ) => {
  42933. let backend = this.backend;
  42934. try {
  42935. await backend.init( this );
  42936. } catch ( error ) {
  42937. if ( this._getFallback !== null ) {
  42938. // try the fallback
  42939. try {
  42940. this.backend = backend = this._getFallback( error );
  42941. await backend.init( this );
  42942. } catch ( error ) {
  42943. reject( error );
  42944. return;
  42945. }
  42946. } else {
  42947. reject( error );
  42948. return;
  42949. }
  42950. }
  42951. this._nodes = new NodeManager( this, backend );
  42952. this._animation = new Animation( this, this._nodes, this.info );
  42953. this._attributes = new Attributes( backend, this.info );
  42954. this._background = new Background( this, this._nodes );
  42955. this._geometries = new Geometries( this._attributes, this.info );
  42956. this._textures = new Textures( this, backend, this.info );
  42957. this._pipelines = new Pipelines( backend, this._nodes, this.info );
  42958. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  42959. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  42960. this._renderLists = new RenderLists( this.lighting );
  42961. this._bundles = new RenderBundles();
  42962. this._renderContexts = new RenderContexts( this );
  42963. //
  42964. this._animation.start();
  42965. this._initialized = true;
  42966. //
  42967. this._inspector.init();
  42968. //
  42969. resolve( this );
  42970. } );
  42971. return this._initPromise;
  42972. }
  42973. /**
  42974. * A reference to the canvas element the renderer is drawing to.
  42975. * This value of this property will automatically be created by
  42976. * the renderer.
  42977. *
  42978. * @type {HTMLCanvasElement|OffscreenCanvas}
  42979. */
  42980. get domElement() {
  42981. return this._canvasTarget.domElement;
  42982. }
  42983. /**
  42984. * The coordinate system of the renderer. The value of this property
  42985. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  42986. * `THREE.WebGPUCoordinateSystem`.
  42987. *
  42988. * @readonly
  42989. * @type {number}
  42990. */
  42991. get coordinateSystem() {
  42992. return this.backend.coordinateSystem;
  42993. }
  42994. /**
  42995. * Compiles all materials in the given scene. This can be useful to avoid a
  42996. * phenomenon which is called "shader compilation stutter", which occurs when
  42997. * rendering an object with a new shader for the first time.
  42998. *
  42999. * If you want to add a 3D object to an existing scene, use the third optional
  43000. * parameter for applying the target scene. Note that the (target) scene's lighting
  43001. * and environment must be configured before calling this method.
  43002. *
  43003. * @async
  43004. * @param {Object3D} scene - The scene or 3D object to precompile.
  43005. * @param {Camera} camera - The camera that is used to render the scene.
  43006. * @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.
  43007. * @return {Promise} A Promise that resolves when the compile has been finished.
  43008. */
  43009. async compileAsync( scene, camera, targetScene = null ) {
  43010. if ( this._isDeviceLost === true ) return;
  43011. if ( this._initialized === false ) await this.init();
  43012. // preserve render tree
  43013. const nodeFrame = this._nodes.nodeFrame;
  43014. const previousRenderId = nodeFrame.renderId;
  43015. const previousRenderContext = this._currentRenderContext;
  43016. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  43017. const previousHandleObjectFunction = this._handleObjectFunction;
  43018. const previousCompilationPromises = this._compilationPromises;
  43019. //
  43020. if ( targetScene === null ) targetScene = scene;
  43021. // Use the actual scene for caching when compiling individual objects
  43022. // This ensures cache keys match between compileAsync and render
  43023. const sceneRef = ( scene.isScene === true ) ? scene : ( targetScene.isScene === true ) ? targetScene : _scene;
  43024. // Match render()'s logic: use frameBufferTarget when needsFrameBufferTarget is true
  43025. const useFrameBufferTarget = this.needsFrameBufferTarget && this._renderTarget === null;
  43026. const renderTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : ( this._renderTarget || this._outputRenderTarget );
  43027. const renderContext = this._renderContexts.get( renderTarget, this._mrt );
  43028. const activeMipmapLevel = this._activeMipmapLevel;
  43029. const compilationPromises = [];
  43030. this._currentRenderContext = renderContext;
  43031. this._currentRenderObjectFunction = this.renderObject;
  43032. this._handleObjectFunction = this._createObjectPipeline;
  43033. this._compilationPromises = compilationPromises;
  43034. nodeFrame.renderId ++;
  43035. //
  43036. nodeFrame.update();
  43037. //
  43038. renderContext.depth = this.depth;
  43039. renderContext.stencil = this.stencil;
  43040. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  43041. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  43042. //
  43043. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  43044. camera = this._updateCamera( camera );
  43045. //
  43046. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  43047. //
  43048. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  43049. if ( ! camera.isArrayCamera ) {
  43050. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  43051. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  43052. }
  43053. // Use sceneRef for render list to ensure lightsNode matches between compileAsync and render
  43054. const renderList = this._renderLists.get( sceneRef, camera );
  43055. renderList.begin();
  43056. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  43057. // include lights from target scene
  43058. if ( targetScene !== scene ) {
  43059. targetScene.traverseVisible( function ( object ) {
  43060. if ( object.isLight && object.layers.test( camera.layers ) ) {
  43061. renderList.pushLight( object );
  43062. }
  43063. } );
  43064. }
  43065. renderList.finish();
  43066. //
  43067. if ( renderTarget !== null ) {
  43068. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  43069. const renderTargetData = this._textures.get( renderTarget );
  43070. renderContext.textures = renderTargetData.textures;
  43071. renderContext.depthTexture = renderTargetData.depthTexture;
  43072. } else {
  43073. renderContext.textures = null;
  43074. renderContext.depthTexture = null;
  43075. }
  43076. //
  43077. if ( targetScene !== scene ) {
  43078. this._background.update( targetScene, renderList, renderContext );
  43079. } else {
  43080. this._background.update( sceneRef, renderList, renderContext );
  43081. }
  43082. // process render lists - _createObjectPipeline will push async promises to _compilationPromises
  43083. const opaqueObjects = renderList.opaque;
  43084. const transparentObjects = renderList.transparent;
  43085. const transparentDoublePassObjects = renderList.transparentDoublePass;
  43086. const lightsNode = renderList.lightsNode;
  43087. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  43088. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  43089. // restore render tree
  43090. nodeFrame.renderId = previousRenderId;
  43091. this._currentRenderContext = previousRenderContext;
  43092. this._currentRenderObjectFunction = previousRenderObjectFunction;
  43093. this._handleObjectFunction = previousHandleObjectFunction;
  43094. this._compilationPromises = previousCompilationPromises;
  43095. // Process compilation work items sequentially to avoid freezing
  43096. // Yields between objects to keep animation smooth
  43097. for ( const item of compilationPromises ) {
  43098. const renderObject = this._objects.get( item.object, item.material, item.scene, item.camera, item.lightsNode, item.renderContext, item.clippingContext, item.passId );
  43099. renderObject.drawRange = item.object.geometry.drawRange;
  43100. renderObject.group = item.group;
  43101. // Use async node building to yield to main thread
  43102. await this._nodes.getForRenderAsync( renderObject );
  43103. this._nodes.updateBefore( renderObject );
  43104. this._geometries.updateForRender( renderObject );
  43105. this._nodes.updateForRender( renderObject );
  43106. this._bindings.updateForRender( renderObject );
  43107. // Wait for pipeline creation
  43108. const pipelinePromises = [];
  43109. this._pipelines.getForRender( renderObject, pipelinePromises );
  43110. if ( pipelinePromises.length > 0 ) {
  43111. await Promise.all( pipelinePromises );
  43112. }
  43113. this._nodes.updateAfter( renderObject );
  43114. // Yield between objects to allow animation frames
  43115. await yieldToMain();
  43116. }
  43117. }
  43118. /**
  43119. * Renders the scene in an async fashion.
  43120. *
  43121. * @async
  43122. * @deprecated
  43123. * @param {Object3D} scene - The scene or 3D object to render.
  43124. * @param {Camera} camera - The camera.
  43125. * @return {Promise} A Promise that resolves when the render has been finished.
  43126. */
  43127. async renderAsync( scene, camera ) {
  43128. warnOnce( 'Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  43129. await this.init();
  43130. this.render( scene, camera );
  43131. }
  43132. /**
  43133. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  43134. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  43135. *
  43136. * @async
  43137. * @deprecated
  43138. * @return {Promise} A Promise that resolves when synchronization has been finished.
  43139. */
  43140. async waitForGPU() {
  43141. error( 'Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.' );
  43142. }
  43143. //
  43144. set inspector( value ) {
  43145. if ( this._inspector !== null ) {
  43146. this._inspector.setRenderer( null );
  43147. }
  43148. this._inspector = value;
  43149. this._inspector.setRenderer( this );
  43150. }
  43151. /**
  43152. * The inspector instance. The inspector can be any class that extends from `InspectorBase`.
  43153. *
  43154. * @type {InspectorBase}
  43155. */
  43156. get inspector() {
  43157. return this._inspector;
  43158. }
  43159. /**
  43160. * Enables or disables high precision for model-view and normal-view matrices.
  43161. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  43162. *
  43163. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  43164. *
  43165. * @param {boolean} value - Whether to enable or disable high precision.
  43166. * @type {boolean}
  43167. */
  43168. set highPrecision( value ) {
  43169. const contextNodeData = this.contextNode.value;
  43170. if ( value === true ) {
  43171. contextNodeData.modelViewMatrix = highpModelViewMatrix;
  43172. contextNodeData.modelNormalViewMatrix = highpModelNormalViewMatrix;
  43173. } else if ( this.highPrecision ) {
  43174. delete contextNodeData.modelViewMatrix;
  43175. delete contextNodeData.modelNormalViewMatrix;
  43176. }
  43177. }
  43178. /**
  43179. * Returns whether high precision is enabled or not.
  43180. *
  43181. * @return {boolean} Whether high precision is enabled or not.
  43182. * @type {boolean}
  43183. */
  43184. get highPrecision() {
  43185. const contextNodeData = this.contextNode.value;
  43186. return contextNodeData.modelViewMatrix === highpModelViewMatrix && contextNodeData.modelNormalViewMatrix === highpModelNormalViewMatrix;
  43187. }
  43188. /**
  43189. * Sets the given MRT configuration.
  43190. *
  43191. * @param {MRTNode} mrt - The MRT node to set.
  43192. * @return {Renderer} A reference to this renderer.
  43193. */
  43194. setMRT( mrt ) {
  43195. this._mrt = mrt;
  43196. return this;
  43197. }
  43198. /**
  43199. * Returns the MRT configuration.
  43200. *
  43201. * @return {MRTNode} The MRT configuration.
  43202. */
  43203. getMRT() {
  43204. return this._mrt;
  43205. }
  43206. /**
  43207. * Returns the output buffer type.
  43208. *
  43209. * @return {number} The output buffer type.
  43210. */
  43211. getOutputBufferType() {
  43212. return this._outputBufferType;
  43213. }
  43214. /**
  43215. * Returns the output buffer type.
  43216. *
  43217. * @deprecated since r182. Use `.getOutputBufferType()` instead.
  43218. * @return {number} The output buffer type.
  43219. */
  43220. getColorBufferType() { // @deprecated, r182
  43221. warnOnce( 'Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".' );
  43222. return this.getOutputBufferType();
  43223. }
  43224. /**
  43225. * Default implementation of the device lost callback.
  43226. *
  43227. * @private
  43228. * @param {Object} info - Information about the context lost.
  43229. */
  43230. _onDeviceLost( info ) {
  43231. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  43232. if ( info.reason ) {
  43233. errorMessage += `\nReason: ${info.reason}`;
  43234. }
  43235. error( errorMessage );
  43236. this._isDeviceLost = true;
  43237. }
  43238. /**
  43239. * Default implementation of the uncaptured backend error callback.
  43240. *
  43241. * @private
  43242. * @param {Object} info - Information about the uncaptured error.
  43243. */
  43244. _onError( info ) {
  43245. let errorMessage = `WebGPURenderer: Uncaptured ${ info.api } ${ info.type }`;
  43246. if ( info.message ) {
  43247. errorMessage += `: ${ info.message }`;
  43248. }
  43249. error( errorMessage );
  43250. }
  43251. /**
  43252. * Renders the given render bundle.
  43253. *
  43254. * @private
  43255. * @param {Object} bundle - Render bundle data.
  43256. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  43257. * @param {LightsNode} lightsNode - The lights node.
  43258. */
  43259. _renderBundle( bundle, sceneRef, lightsNode ) {
  43260. const { bundleGroup, camera, renderList } = bundle;
  43261. const renderContext = this._currentRenderContext;
  43262. //
  43263. const renderBundle = this._bundles.get( bundleGroup, camera, renderContext );
  43264. const renderBundleData = this.backend.get( renderBundle );
  43265. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  43266. const renderBundleNeedsUpdate = needsUpdate || renderBundleData.bundleGPU === undefined;
  43267. if ( renderBundleNeedsUpdate ) {
  43268. this.backend.beginBundle( renderContext );
  43269. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  43270. renderBundleData.renderObjects = [];
  43271. }
  43272. this._currentRenderBundle = renderBundle;
  43273. const {
  43274. transparentDoublePass: transparentDoublePassObjects,
  43275. transparent: transparentObjects,
  43276. opaque: opaqueObjects
  43277. } = renderList;
  43278. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  43279. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  43280. this._currentRenderBundle = null;
  43281. //
  43282. this.backend.finishBundle( renderContext, renderBundle );
  43283. renderBundleData.version = bundleGroup.version;
  43284. } else {
  43285. const { renderObjects } = renderBundleData;
  43286. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  43287. const renderObject = renderObjects[ i ];
  43288. if ( this._nodes.needsRefresh( renderObject ) ) {
  43289. this._nodes.updateBefore( renderObject );
  43290. this._nodes.updateForRender( renderObject );
  43291. this._bindings.updateForRender( renderObject );
  43292. this._nodes.updateAfter( renderObject );
  43293. }
  43294. }
  43295. }
  43296. this.backend.addBundle( renderContext, renderBundle );
  43297. }
  43298. /**
  43299. * Renders the scene or 3D object with the given camera. This method can only be called
  43300. * if the renderer has been initialized. When using `render()` inside an animation loop,
  43301. * it's guaranteed the renderer will be initialized. The animation loop must be defined
  43302. * with {@link Renderer#setAnimationLoop} though.
  43303. *
  43304. * For all other use cases (like when using on-demand rendering), you must call
  43305. * {@link Renderer#init} before rendering.
  43306. *
  43307. * The target of the method is the default framebuffer (meaning the canvas)
  43308. * or alternatively a render target when specified via `setRenderTarget()`.
  43309. *
  43310. * @param {Object3D} scene - The scene or 3D object to render.
  43311. * @param {Camera} camera - The camera to render the scene with.
  43312. */
  43313. render( scene, camera ) {
  43314. if ( this._initialized === false ) {
  43315. throw new Error( 'THREE.Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.' );
  43316. }
  43317. this._renderScene( scene, camera );
  43318. }
  43319. /**
  43320. * Returns whether the renderer has been initialized or not.
  43321. *
  43322. * @readonly
  43323. * @return {boolean} Whether the renderer has been initialized or not.
  43324. */
  43325. get initialized() {
  43326. return this._initialized;
  43327. }
  43328. _renderOutputLayers( quad, renderTarget ) {
  43329. if ( renderTarget.texture.isArrayTexture !== true || renderTarget.texture.image.depth <= 1 ) {
  43330. this._renderScene( quad, quad.camera, false );
  43331. return;
  43332. }
  43333. const currentActiveCubeFace = this._activeCubeFace;
  43334. try {
  43335. for ( let layer = 0; layer < renderTarget.texture.image.depth; layer ++ ) {
  43336. this._nodes.setOutputLayerIndex( layer );
  43337. this._activeCubeFace = layer;
  43338. this._renderScene( quad, quad.camera, false );
  43339. }
  43340. } finally {
  43341. this._nodes.setOutputLayerIndex( 0 );
  43342. this._activeCubeFace = currentActiveCubeFace;
  43343. }
  43344. }
  43345. /**
  43346. * Returns an internal render target which is used when computing the output tone mapping
  43347. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  43348. * pass and not inline to achieve more correct results.
  43349. *
  43350. * @private
  43351. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  43352. */
  43353. _getFrameBufferTarget() {
  43354. const { currentToneMapping, currentColorSpace } = this;
  43355. const useToneMapping = currentToneMapping !== NoToneMapping;
  43356. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  43357. if ( useToneMapping === false && useColorSpace === false ) return null;
  43358. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  43359. const { depth, stencil } = this;
  43360. // TODO: Unify CanvasTarget and OutputRenderTarget
  43361. const target = this._outputRenderTarget || this._canvasTarget;
  43362. let frameBufferTarget = this._frameBufferTargets.get( target );
  43363. if ( frameBufferTarget === undefined ) {
  43364. frameBufferTarget = new RenderTarget( width, height, {
  43365. depthBuffer: depth,
  43366. stencilBuffer: stencil,
  43367. type: this._outputBufferType,
  43368. format: RGBAFormat,
  43369. colorSpace: ColorManagement.workingColorSpace,
  43370. generateMipmaps: false,
  43371. minFilter: LinearFilter,
  43372. magFilter: LinearFilter,
  43373. samples: this.samples
  43374. } );
  43375. frameBufferTarget.isPostProcessingRenderTarget = true;
  43376. const dispose = () => {
  43377. target.removeEventListener( 'dispose', dispose );
  43378. frameBufferTarget.dispose();
  43379. this._frameBufferTargets.delete( target );
  43380. };
  43381. target.addEventListener( 'dispose', dispose );
  43382. this._frameBufferTargets.set( target, frameBufferTarget );
  43383. }
  43384. const outputRenderTarget = this.getOutputRenderTarget();
  43385. frameBufferTarget.depthBuffer = depth;
  43386. frameBufferTarget.stencilBuffer = stencil;
  43387. if ( outputRenderTarget !== null ) {
  43388. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  43389. } else {
  43390. frameBufferTarget.setSize( width, height, 1 );
  43391. }
  43392. // RenderTarget || CanvasTarget
  43393. const viewport = this._outputRenderTarget ? this._outputRenderTarget.viewport : target._viewport;
  43394. const scissor = this._outputRenderTarget ? this._outputRenderTarget.scissor : target._scissor;
  43395. const pixelRatio = this._outputRenderTarget ? 1 : target._pixelRatio;
  43396. const scissorTest = this._outputRenderTarget ? this._outputRenderTarget.scissorTest : target._scissorTest;
  43397. frameBufferTarget.viewport.copy( viewport );
  43398. frameBufferTarget.scissor.copy( scissor );
  43399. frameBufferTarget.viewport.multiplyScalar( pixelRatio );
  43400. frameBufferTarget.scissor.multiplyScalar( pixelRatio );
  43401. frameBufferTarget.scissorTest = scissorTest;
  43402. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  43403. frameBufferTarget.useArrayDepthTexture = outputRenderTarget !== null ? outputRenderTarget.useArrayDepthTexture : false;
  43404. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  43405. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  43406. return frameBufferTarget;
  43407. }
  43408. /**
  43409. * Renders the scene or 3D object with the given camera.
  43410. *
  43411. * @private
  43412. * @param {Object3D} scene - The scene or 3D object to render.
  43413. * @param {Camera} camera - The camera to render the scene with.
  43414. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  43415. * @return {RenderContext} The current render context.
  43416. */
  43417. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  43418. if ( this._isDeviceLost === true ) return;
  43419. //
  43420. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  43421. // preserve render tree
  43422. const nodeFrame = this._nodes.nodeFrame;
  43423. const previousRenderId = nodeFrame.renderId;
  43424. const previousRenderContext = this._currentRenderContext;
  43425. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  43426. const previousHandleObjectFunction = this._handleObjectFunction;
  43427. this.lighting.beginRender( scene );
  43428. //
  43429. this._callDepth ++;
  43430. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  43431. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  43432. const activeCubeFace = this._activeCubeFace;
  43433. const activeMipmapLevel = this._activeMipmapLevel;
  43434. //
  43435. let renderTarget;
  43436. if ( frameBufferTarget !== null ) {
  43437. renderTarget = frameBufferTarget;
  43438. this.setRenderTarget( renderTarget );
  43439. } else {
  43440. renderTarget = outputRenderTarget;
  43441. }
  43442. // make sure a new render target has correct default depth values
  43443. if ( renderTarget !== null && renderTarget.depthBuffer === true ) {
  43444. const renderTargetData = this._textures.get( renderTarget );
  43445. if ( renderTargetData.depthInitialized !== true ) {
  43446. // we need a single manual clear if auto clear depth is disabled
  43447. if ( this.autoClear === false || ( this.autoClear === true && this.autoClearDepth === false ) ) {
  43448. this.clearDepth();
  43449. }
  43450. renderTargetData.depthInitialized = true;
  43451. }
  43452. }
  43453. //
  43454. const renderContext = this._renderContexts.get( renderTarget, this._mrt, this._callDepth );
  43455. this._currentRenderContext = renderContext;
  43456. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  43457. this._handleObjectFunction = this._renderObjectDirect;
  43458. //
  43459. this.info.calls ++;
  43460. this.info.render.calls ++;
  43461. this.info.render.frameCalls ++;
  43462. nodeFrame.renderId = this.info.calls;
  43463. //
  43464. this.backend.updateTimeStampUID( renderContext );
  43465. this.inspector.beginRender( this.backend.getTimestampUID( renderContext ), scene, camera, renderTarget );
  43466. //
  43467. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  43468. camera = this._updateCamera( camera );
  43469. //
  43470. const canvasTarget = this._canvasTarget;
  43471. let viewport = canvasTarget._viewport;
  43472. let scissor = canvasTarget._scissor;
  43473. let pixelRatio = canvasTarget._pixelRatio;
  43474. if ( renderTarget !== null ) {
  43475. viewport = renderTarget.viewport;
  43476. scissor = renderTarget.scissor;
  43477. pixelRatio = 1;
  43478. }
  43479. this.getDrawingBufferSize( _drawingBufferSize );
  43480. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  43481. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  43482. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  43483. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  43484. renderContext.viewportValue.width >>= activeMipmapLevel;
  43485. renderContext.viewportValue.height >>= activeMipmapLevel;
  43486. renderContext.viewportValue.minDepth = minDepth;
  43487. renderContext.viewportValue.maxDepth = maxDepth;
  43488. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  43489. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  43490. renderContext.scissor = canvasTarget._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  43491. renderContext.scissorValue.width >>= activeMipmapLevel;
  43492. renderContext.scissorValue.height >>= activeMipmapLevel;
  43493. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  43494. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  43495. //
  43496. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  43497. //
  43498. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  43499. if ( ! camera.isArrayCamera ) {
  43500. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  43501. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  43502. }
  43503. const renderList = this._renderLists.get( scene, camera );
  43504. renderList.begin();
  43505. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  43506. renderList.finish();
  43507. if ( this.sortObjects === true ) {
  43508. renderList.sort( this._opaqueSort, this._transparentSort, camera.reversedDepth );
  43509. }
  43510. //
  43511. if ( renderTarget !== null ) {
  43512. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  43513. const renderTargetData = this._textures.get( renderTarget );
  43514. renderContext.textures = renderTargetData.textures;
  43515. renderContext.depthTexture = renderTargetData.depthTexture;
  43516. renderContext.width = renderTargetData.width;
  43517. renderContext.height = renderTargetData.height;
  43518. renderContext.renderTarget = renderTarget;
  43519. renderContext.depth = renderTarget.depthBuffer;
  43520. renderContext.stencil = renderTarget.stencilBuffer;
  43521. } else {
  43522. renderContext.textures = null;
  43523. renderContext.depthTexture = null;
  43524. renderContext.width = _drawingBufferSize.width;
  43525. renderContext.height = _drawingBufferSize.height;
  43526. renderContext.depth = this.depth;
  43527. renderContext.stencil = this.stencil;
  43528. }
  43529. renderContext.width >>= activeMipmapLevel;
  43530. renderContext.height >>= activeMipmapLevel;
  43531. renderContext.activeCubeFace = activeCubeFace;
  43532. renderContext.activeMipmapLevel = activeMipmapLevel;
  43533. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  43534. //
  43535. renderContext.scissorValue.max( _vector4.set( 0, 0, 0, 0 ) );
  43536. if ( renderContext.scissorValue.x + renderContext.scissorValue.width > renderContext.width ) {
  43537. renderContext.scissorValue.width = Math.max( renderContext.width - renderContext.scissorValue.x, 0 );
  43538. }
  43539. if ( renderContext.scissorValue.y + renderContext.scissorValue.height > renderContext.height ) {
  43540. renderContext.scissorValue.height = Math.max( renderContext.height - renderContext.scissorValue.y, 0 );
  43541. }
  43542. //
  43543. this._background.update( sceneRef, renderList, renderContext );
  43544. //
  43545. renderContext.camera = camera;
  43546. this.backend.beginRender( renderContext );
  43547. // process render lists
  43548. const {
  43549. bundles,
  43550. lightsNode,
  43551. transparentDoublePass: transparentDoublePassObjects,
  43552. transparent: transparentObjects,
  43553. opaque: opaqueObjects
  43554. } = renderList;
  43555. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  43556. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  43557. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  43558. // finish render pass
  43559. this.backend.finishRender( renderContext );
  43560. // restore render tree
  43561. nodeFrame.renderId = previousRenderId;
  43562. this._currentRenderContext = previousRenderContext;
  43563. this._currentRenderObjectFunction = previousRenderObjectFunction;
  43564. this._handleObjectFunction = previousHandleObjectFunction;
  43565. this.lighting.finishRender( scene );
  43566. //
  43567. this._callDepth --;
  43568. if ( frameBufferTarget !== null ) {
  43569. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  43570. this._renderOutput( renderTarget );
  43571. }
  43572. //
  43573. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  43574. //
  43575. this.inspector.finishRender( this.backend.getTimestampUID( renderContext ) );
  43576. //
  43577. return renderContext;
  43578. }
  43579. _setXRLayerSize( width, height ) {
  43580. // TODO: Find a better solution to resize the canvas when in XR.
  43581. this._canvasTarget._width = width;
  43582. this._canvasTarget._height = height;
  43583. this.setViewport( 0, 0, width, height );
  43584. }
  43585. /**
  43586. * The output pass performs tone mapping and color space conversion.
  43587. *
  43588. * @private
  43589. * @param {RenderTarget} renderTarget - The current render target.
  43590. */
  43591. _renderOutput( renderTarget ) {
  43592. const cacheKey = this._nodes.getOutputCacheKey();
  43593. let quadData = this._quadCache.get( renderTarget.texture );
  43594. let quad;
  43595. if ( quadData === undefined ) {
  43596. quad = new QuadMesh( new NodeMaterial() );
  43597. quad.name = 'Output Color Transform';
  43598. quad.material.name = 'outputColorTransform';
  43599. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  43600. quadData = {
  43601. quad,
  43602. cacheKey
  43603. };
  43604. this._quadCache.set( renderTarget.texture, quadData );
  43605. // dispose logic
  43606. const dispose = () => {
  43607. quad.material.dispose();
  43608. this._quadCache.delete( renderTarget.texture );
  43609. renderTarget.texture.removeEventListener( 'dispose', dispose );
  43610. };
  43611. renderTarget.texture.addEventListener( 'dispose', dispose );
  43612. } else {
  43613. quad = quadData.quad;
  43614. if ( quadData.cacheKey !== cacheKey ) {
  43615. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  43616. quad.material.needsUpdate = true;
  43617. quadData.cacheKey = cacheKey;
  43618. }
  43619. }
  43620. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  43621. const currentAutoClear = this.autoClear;
  43622. const currentXR = this.xr.enabled;
  43623. this.autoClear = false;
  43624. this.xr.enabled = false;
  43625. this._renderOutputLayers( quad, renderTarget );
  43626. this.autoClear = currentAutoClear;
  43627. this.xr.enabled = currentXR;
  43628. }
  43629. /**
  43630. * Returns the maximum available anisotropy for texture filtering.
  43631. *
  43632. * @return {number} The maximum available anisotropy.
  43633. */
  43634. getMaxAnisotropy() {
  43635. return this.backend.capabilities.getMaxAnisotropy();
  43636. }
  43637. /**
  43638. * Returns the active cube face.
  43639. *
  43640. * @return {number} The active cube face.
  43641. */
  43642. getActiveCubeFace() {
  43643. return this._activeCubeFace;
  43644. }
  43645. /**
  43646. * Returns the active mipmap level.
  43647. *
  43648. * @return {number} The active mipmap level.
  43649. */
  43650. getActiveMipmapLevel() {
  43651. return this._activeMipmapLevel;
  43652. }
  43653. /**
  43654. * Applications are advised to always define the animation loop
  43655. * with this method and not manually with `requestAnimationFrame()`
  43656. * for best compatibility.
  43657. *
  43658. * @async
  43659. * @param {?onAnimationCallback} callback - The application's animation loop.
  43660. * @return {Promise} A Promise that resolves when the set has been executed.
  43661. */
  43662. async setAnimationLoop( callback ) {
  43663. if ( this._initialized === false ) await this.init();
  43664. this._animation.setAnimationLoop( callback );
  43665. }
  43666. /**
  43667. * Returns the current animation loop callback.
  43668. *
  43669. * @return {?Function} The current animation loop callback.
  43670. */
  43671. getAnimationLoop() {
  43672. return this._animation.getAnimationLoop();
  43673. }
  43674. /**
  43675. * Can be used to transfer buffer data from a storage buffer attribute
  43676. * from the GPU to the CPU in context of compute shaders.
  43677. *
  43678. * @async
  43679. * @param {BufferAttribute} attribute - The storage buffer attribute to read frm.
  43680. * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute.
  43681. * @param {number} offset - The storage buffer attribute.
  43682. * @param {number} count - The offset from which to start reading the
  43683. * @return {Promise<ArrayBuffer|ReadbackBuffer>} A promise that resolves with the buffer data when the data are ready.
  43684. */
  43685. async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) {
  43686. // tally the memory for this readback buffer
  43687. if ( target !== null && target.isReadbackBuffer ) {
  43688. if ( this.info.memoryMap.has( target ) === false ) {
  43689. this.info.createReadbackBuffer( target );
  43690. const disposeInfo = () => {
  43691. target.removeEventListener( 'dispose', disposeInfo );
  43692. this.info.destroyReadbackBuffer( target );
  43693. };
  43694. target.addEventListener( 'dispose', disposeInfo );
  43695. }
  43696. }
  43697. if ( offset % 4 !== 0 || ( count > 0 && count % 4 !== 0 ) ) {
  43698. throw new Error( 'THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.' );
  43699. }
  43700. return await this.backend.getArrayBufferAsync( attribute, target, offset, count );
  43701. }
  43702. /**
  43703. * Returns the rendering context.
  43704. *
  43705. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  43706. */
  43707. getContext() {
  43708. return this.backend.getContext();
  43709. }
  43710. /**
  43711. * Returns the pixel ratio.
  43712. *
  43713. * @return {number} The pixel ratio.
  43714. */
  43715. getPixelRatio() {
  43716. return this._canvasTarget.getPixelRatio();
  43717. }
  43718. /**
  43719. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  43720. *
  43721. * @param {Vector2} target - The method writes the result in this target object.
  43722. * @return {Vector2} The drawing buffer size.
  43723. */
  43724. getDrawingBufferSize( target ) {
  43725. return this._canvasTarget.getDrawingBufferSize( target );
  43726. }
  43727. /**
  43728. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  43729. *
  43730. * @param {Vector2} target - The method writes the result in this target object.
  43731. * @return {Vector2} The renderer's size in logical pixels.
  43732. */
  43733. getSize( target ) {
  43734. return this._canvasTarget.getSize( target );
  43735. }
  43736. /**
  43737. * Sets the given pixel ratio and resizes the canvas if necessary.
  43738. *
  43739. * @param {number} [value=1] - The pixel ratio.
  43740. */
  43741. setPixelRatio( value = 1 ) {
  43742. this._canvasTarget.setPixelRatio( value );
  43743. }
  43744. /**
  43745. * This method allows to define the drawing buffer size by specifying
  43746. * width, height and pixel ratio all at once. The size of the drawing
  43747. * buffer is computed with this formula:
  43748. * ```js
  43749. * size.x = width * pixelRatio;
  43750. * size.y = height * pixelRatio;
  43751. * ```
  43752. *
  43753. * @param {number} width - The width in logical pixels.
  43754. * @param {number} height - The height in logical pixels.
  43755. * @param {number} pixelRatio - The pixel ratio.
  43756. */
  43757. setDrawingBufferSize( width, height, pixelRatio ) {
  43758. // Renderer can't be resized while presenting in XR.
  43759. if ( this.xr && this.xr.isPresenting ) return;
  43760. this._canvasTarget.setDrawingBufferSize( width, height, pixelRatio );
  43761. }
  43762. /**
  43763. * Sets the size of the renderer.
  43764. *
  43765. * @param {number} width - The width in logical pixels.
  43766. * @param {number} height - The height in logical pixels.
  43767. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  43768. */
  43769. setSize( width, height, updateStyle = true ) {
  43770. // Renderer can't be resized while presenting in XR.
  43771. if ( this.xr && this.xr.isPresenting ) return;
  43772. this._canvasTarget.setSize( width, height, updateStyle );
  43773. }
  43774. /**
  43775. * Defines a manual sort function for the opaque render list.
  43776. * Pass `null` to use the default sort.
  43777. *
  43778. * @param {Function} method - The sort function.
  43779. */
  43780. setOpaqueSort( method ) {
  43781. this._opaqueSort = method;
  43782. }
  43783. /**
  43784. * Defines a manual sort function for the transparent render list.
  43785. * Pass `null` to use the default sort.
  43786. *
  43787. * @param {Function} method - The sort function.
  43788. */
  43789. setTransparentSort( method ) {
  43790. this._transparentSort = method;
  43791. }
  43792. /**
  43793. * Returns the scissor rectangle.
  43794. *
  43795. * @param {Vector4} target - The method writes the result in this target object.
  43796. * @return {Vector4} The scissor rectangle.
  43797. */
  43798. getScissor( target ) {
  43799. return this._canvasTarget.getScissor( target );
  43800. }
  43801. /**
  43802. * Defines the scissor rectangle.
  43803. *
  43804. * @param {number | Vector4} x - The horizontal coordinate for the upper left corner of the box in logical pixel unit.
  43805. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  43806. * @param {number} y - The vertical coordinate for the upper left corner of the box in logical pixel unit.
  43807. * @param {number} width - The width of the scissor box in logical pixel unit.
  43808. * @param {number} height - The height of the scissor box in logical pixel unit.
  43809. */
  43810. setScissor( x, y, width, height ) {
  43811. this._canvasTarget.setScissor( x, y, width, height );
  43812. }
  43813. /**
  43814. * Returns the scissor test value.
  43815. *
  43816. * @return {boolean} Whether the scissor test should be enabled or not.
  43817. */
  43818. getScissorTest() {
  43819. return this._canvasTarget.getScissorTest();
  43820. }
  43821. /**
  43822. * Defines the scissor test.
  43823. *
  43824. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  43825. */
  43826. setScissorTest( boolean ) {
  43827. this._canvasTarget.setScissorTest( boolean );
  43828. // TODO: Move it to CanvasTarget event listener.
  43829. this.backend.setScissorTest( boolean );
  43830. }
  43831. /**
  43832. * Returns the viewport definition.
  43833. *
  43834. * @param {Vector4} target - The method writes the result in this target object.
  43835. * @return {Vector4} The viewport definition.
  43836. */
  43837. getViewport( target ) {
  43838. return this._canvasTarget.getViewport( target );
  43839. }
  43840. /**
  43841. * Defines the viewport.
  43842. *
  43843. * @param {number | Vector4} x - The horizontal coordinate for the upper left corner of the viewport origin in logical pixel unit.
  43844. * @param {number} y - The vertical coordinate for the upper left corner of the viewport origin in logical pixel unit.
  43845. * @param {number} width - The width of the viewport in logical pixel unit.
  43846. * @param {number} height - The height of the viewport in logical pixel unit.
  43847. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  43848. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  43849. */
  43850. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  43851. this._canvasTarget.setViewport( x, y, width, height, minDepth, maxDepth );
  43852. }
  43853. /**
  43854. * Returns the clear color.
  43855. *
  43856. * @param {Color} target - The method writes the result in this target object.
  43857. * @return {Color} The clear color.
  43858. */
  43859. getClearColor( target ) {
  43860. return target.copy( this._clearColor );
  43861. }
  43862. /**
  43863. * Defines the clear color and optionally the clear alpha.
  43864. *
  43865. * @param {Color} color - The clear color.
  43866. * @param {number} [alpha=1] - The clear alpha.
  43867. */
  43868. setClearColor( color, alpha = 1 ) {
  43869. this._clearColor.set( color );
  43870. this._clearColor.a = alpha;
  43871. }
  43872. /**
  43873. * Returns the clear alpha.
  43874. *
  43875. * @return {number} The clear alpha.
  43876. */
  43877. getClearAlpha() {
  43878. return this._clearColor.a;
  43879. }
  43880. /**
  43881. * Defines the clear alpha.
  43882. *
  43883. * @param {number} alpha - The clear alpha.
  43884. */
  43885. setClearAlpha( alpha ) {
  43886. this._clearColor.a = alpha;
  43887. }
  43888. /**
  43889. * Returns the clear depth.
  43890. *
  43891. * @return {number} The clear depth.
  43892. */
  43893. getClearDepth() {
  43894. return ( this.reversedDepthBuffer === true ) ? 1 - this._clearDepth : this._clearDepth;
  43895. }
  43896. /**
  43897. * Defines the clear depth.
  43898. *
  43899. * @param {number} depth - The clear depth.
  43900. */
  43901. setClearDepth( depth ) {
  43902. this._clearDepth = depth;
  43903. }
  43904. /**
  43905. * Returns the clear stencil.
  43906. *
  43907. * @return {number} The clear stencil.
  43908. */
  43909. getClearStencil() {
  43910. return this._clearStencil;
  43911. }
  43912. /**
  43913. * Defines the clear stencil.
  43914. *
  43915. * @param {number} stencil - The clear stencil.
  43916. */
  43917. setClearStencil( stencil ) {
  43918. this._clearStencil = stencil;
  43919. }
  43920. /**
  43921. * This method performs an occlusion query for the given 3D object.
  43922. * It returns `true` if the given 3D object is fully occluded by other
  43923. * 3D objects in the scene.
  43924. *
  43925. * @param {Object3D} object - The 3D object to test.
  43926. * @return {boolean} Whether the 3D object is fully occluded or not.
  43927. */
  43928. isOccluded( object ) {
  43929. const renderContext = this._currentRenderContext;
  43930. return renderContext && this.backend.isOccluded( renderContext, object );
  43931. }
  43932. /**
  43933. * Performs a manual clear operation. This method ignores `autoClear` properties.
  43934. *
  43935. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  43936. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  43937. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  43938. */
  43939. clear( color = true, depth = true, stencil = true ) {
  43940. if ( this._initialized === false ) {
  43941. throw new Error( 'THREE.Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before using this method.' );
  43942. }
  43943. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  43944. let renderContext = null;
  43945. if ( renderTarget !== null ) {
  43946. this._textures.updateRenderTarget( renderTarget );
  43947. const renderTargetData = this._textures.get( renderTarget );
  43948. renderContext = this._renderContexts.get( renderTarget, null, -1 ); // using - 1 for the call depth to get a render context for the clear operation
  43949. renderContext.textures = renderTargetData.textures;
  43950. renderContext.depthTexture = renderTargetData.depthTexture;
  43951. renderContext.width = renderTargetData.width;
  43952. renderContext.height = renderTargetData.height;
  43953. renderContext.renderTarget = renderTarget;
  43954. renderContext.depth = renderTarget.depthBuffer;
  43955. renderContext.stencil = renderTarget.stencilBuffer;
  43956. // #30329
  43957. const color = this.backend.getClearColor();
  43958. renderContext.clearColorValue.r = color.r;
  43959. renderContext.clearColorValue.g = color.g;
  43960. renderContext.clearColorValue.b = color.b;
  43961. renderContext.clearColorValue.a = color.a;
  43962. renderContext.clearDepthValue = this.getClearDepth();
  43963. renderContext.clearStencilValue = this.getClearStencil();
  43964. renderContext.activeCubeFace = this.getActiveCubeFace();
  43965. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  43966. if ( renderTarget.depthBuffer === true ) renderTargetData.depthInitialized = true;
  43967. }
  43968. this.backend.clear( color, depth, stencil, renderContext );
  43969. if ( renderTarget !== null && this._renderTarget === null ) {
  43970. this._renderOutput( renderTarget );
  43971. }
  43972. }
  43973. /**
  43974. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  43975. */
  43976. clearColor() {
  43977. this.clear( true, false, false );
  43978. }
  43979. /**
  43980. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  43981. */
  43982. clearDepth() {
  43983. this.clear( false, true, false );
  43984. }
  43985. /**
  43986. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  43987. */
  43988. clearStencil() {
  43989. this.clear( false, false, true );
  43990. }
  43991. /**
  43992. * Async version of {@link Renderer#clear}.
  43993. *
  43994. * @async
  43995. * @deprecated
  43996. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  43997. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  43998. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  43999. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  44000. */
  44001. async clearAsync( color = true, depth = true, stencil = true ) {
  44002. warnOnce( 'Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  44003. await this.init();
  44004. this.clear( color, depth, stencil );
  44005. }
  44006. /**
  44007. * Async version of {@link Renderer#clearColor}.
  44008. *
  44009. * @async
  44010. * @deprecated
  44011. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  44012. */
  44013. async clearColorAsync() {
  44014. warnOnce( 'Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  44015. this.clear( true, false, false );
  44016. }
  44017. /**
  44018. * Async version of {@link Renderer#clearDepth}.
  44019. *
  44020. * @async
  44021. * @deprecated
  44022. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  44023. */
  44024. async clearDepthAsync() {
  44025. warnOnce( 'Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  44026. this.clear( false, true, false );
  44027. }
  44028. /**
  44029. * Async version of {@link Renderer#clearStencil}.
  44030. *
  44031. * @async
  44032. * @deprecated
  44033. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  44034. */
  44035. async clearStencilAsync() {
  44036. warnOnce( 'Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  44037. this.clear( false, false, true );
  44038. }
  44039. /**
  44040. * Returns `true` if a framebuffer target is needed to perform tone mapping or color space conversion.
  44041. * If this is the case, the renderer allocates an internal render target for that purpose.
  44042. *
  44043. */
  44044. get needsFrameBufferTarget() {
  44045. const useToneMapping = this.currentToneMapping !== NoToneMapping;
  44046. const useColorSpace = this.currentColorSpace !== ColorManagement.workingColorSpace;
  44047. return useToneMapping || useColorSpace;
  44048. }
  44049. /**
  44050. * The number of samples used for multi-sample anti-aliasing (MSAA).
  44051. *
  44052. * @type {number}
  44053. * @default 0
  44054. */
  44055. get samples() {
  44056. return this._samples;
  44057. }
  44058. /**
  44059. * The current number of samples used for multi-sample anti-aliasing (MSAA).
  44060. *
  44061. * When rendering to a custom render target, the number of samples of that render target is used.
  44062. * If the renderer needs an internal framebuffer target for tone mapping or color space conversion,
  44063. * the number of samples is set to 0.
  44064. *
  44065. * @type {number}
  44066. */
  44067. get currentSamples() {
  44068. let samples = this._samples;
  44069. if ( this._renderTarget !== null ) {
  44070. samples = this._renderTarget.samples;
  44071. } else if ( this.needsFrameBufferTarget ) {
  44072. samples = 0;
  44073. }
  44074. return samples;
  44075. }
  44076. /**
  44077. * The current tone mapping of the renderer. When not producing screen output,
  44078. * the tone mapping is always `NoToneMapping`.
  44079. *
  44080. * @type {number}
  44081. */
  44082. get currentToneMapping() {
  44083. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  44084. }
  44085. /**
  44086. * The current color space of the renderer. When not producing screen output,
  44087. * the color space is always the working color space.
  44088. *
  44089. * @type {string}
  44090. */
  44091. get currentColorSpace() {
  44092. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  44093. }
  44094. /**
  44095. * Returns `true` if the rendering settings are set to screen output.
  44096. *
  44097. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  44098. */
  44099. get isOutputTarget() {
  44100. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  44101. }
  44102. /**
  44103. * Frees all internal resources of the renderer. Call this method if the renderer
  44104. * is no longer in use by your app.
  44105. */
  44106. dispose() {
  44107. if ( this._initialized === true ) {
  44108. this.info.dispose();
  44109. this.backend.dispose();
  44110. this._animation.dispose();
  44111. this._objects.dispose();
  44112. this._geometries.dispose();
  44113. this._pipelines.dispose();
  44114. this._nodes.dispose();
  44115. this._bindings.dispose();
  44116. this._renderLists.dispose();
  44117. this._renderContexts.dispose();
  44118. this._textures.dispose();
  44119. for ( const canvasTarget of this._frameBufferTargets.keys() ) {
  44120. canvasTarget.dispose();
  44121. }
  44122. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  44123. if ( queryPool !== null ) queryPool.dispose();
  44124. } );
  44125. }
  44126. this.setRenderTarget( null );
  44127. this.setAnimationLoop( null );
  44128. }
  44129. /**
  44130. * Sets the given render target. Calling this method means the renderer does not
  44131. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  44132. * Use `null` as the first argument to reset the state.
  44133. *
  44134. * @param {?RenderTarget} renderTarget - The render target to set.
  44135. * @param {number} [activeCubeFace=0] - The active cube face.
  44136. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  44137. */
  44138. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  44139. this._renderTarget = renderTarget;
  44140. this._activeCubeFace = activeCubeFace;
  44141. this._activeMipmapLevel = activeMipmapLevel;
  44142. }
  44143. /**
  44144. * Returns the current render target.
  44145. *
  44146. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  44147. */
  44148. getRenderTarget() {
  44149. return this._renderTarget;
  44150. }
  44151. /**
  44152. * Sets the output render target for the renderer.
  44153. *
  44154. * @param {?RenderTarget} renderTarget - The render target to set as the output target.
  44155. */
  44156. setOutputRenderTarget( renderTarget ) {
  44157. this._outputRenderTarget = renderTarget;
  44158. }
  44159. /**
  44160. * Returns the current output target.
  44161. *
  44162. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  44163. */
  44164. getOutputRenderTarget() {
  44165. return this._outputRenderTarget;
  44166. }
  44167. /**
  44168. * Sets the canvas target. The canvas target manages the HTML canvas
  44169. * or the offscreen canvas the renderer draws into.
  44170. *
  44171. * @param {CanvasTarget} canvasTarget - The canvas target.
  44172. */
  44173. setCanvasTarget( canvasTarget ) {
  44174. this._canvasTarget.removeEventListener( 'resize', this._onCanvasTargetResize );
  44175. this._canvasTarget = canvasTarget;
  44176. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  44177. }
  44178. /**
  44179. * Returns the current canvas target.
  44180. *
  44181. * @return {CanvasTarget} The current canvas target.
  44182. */
  44183. getCanvasTarget() {
  44184. return this._canvasTarget;
  44185. }
  44186. /**
  44187. * Resets the renderer to the initial state before WebXR started.
  44188. *
  44189. * @private
  44190. */
  44191. _resetXRState() {
  44192. this.backend.setXRTarget( null );
  44193. this.setOutputRenderTarget( null );
  44194. this.setRenderTarget( null );
  44195. for ( const canvasTarget of this._frameBufferTargets.keys() ) {
  44196. canvasTarget.dispose();
  44197. }
  44198. }
  44199. /**
  44200. * Callback for {@link Renderer#setRenderObjectFunction}.
  44201. *
  44202. * @callback renderObjectFunction
  44203. * @param {Object3D} object - The 3D object.
  44204. * @param {Scene} scene - The scene the 3D object belongs to.
  44205. * @param {Camera} camera - The camera the object should be rendered with.
  44206. * @param {BufferGeometry} geometry - The object's geometry.
  44207. * @param {Material} material - The object's material.
  44208. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  44209. * @param {LightsNode} lightsNode - The current lights node.
  44210. * @param {ClippingContext} clippingContext - The clipping context.
  44211. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  44212. */
  44213. /**
  44214. * Sets the given render object function. Calling this method overwrites the default implementation
  44215. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  44216. * if you want to modify the way objects are rendered. For example you can define things like "every
  44217. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  44218. * The custom function must always call `renderObject()` in its implementation.
  44219. *
  44220. * Use `null` as the first argument to reset the state.
  44221. *
  44222. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  44223. */
  44224. setRenderObjectFunction( renderObjectFunction ) {
  44225. this._renderObjectFunction = renderObjectFunction;
  44226. }
  44227. /**
  44228. * Returns the current render object function.
  44229. *
  44230. * @return {?Function} The current render object function. Returns `null` if no function is set.
  44231. */
  44232. getRenderObjectFunction() {
  44233. return this._renderObjectFunction;
  44234. }
  44235. /**
  44236. * Execute a single or an array of compute nodes. This method can only be called
  44237. * if the renderer has been initialized.
  44238. *
  44239. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  44240. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  44241. * - A single number representing count, or
  44242. * - An array [x, y, z] representing dispatch size, or
  44243. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  44244. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  44245. */
  44246. compute( computeNodes, dispatchSize = null ) {
  44247. if ( this._isDeviceLost === true ) return;
  44248. if ( this._initialized === false ) {
  44249. warn( 'Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  44250. return this.computeAsync( computeNodes, dispatchSize );
  44251. }
  44252. //
  44253. const nodeFrame = this._nodes.nodeFrame;
  44254. const previousRenderId = nodeFrame.renderId;
  44255. //
  44256. this.info.calls ++;
  44257. this.info.compute.calls ++;
  44258. this.info.compute.frameCalls ++;
  44259. nodeFrame.renderId = this.info.calls;
  44260. //
  44261. this.backend.updateTimeStampUID( computeNodes );
  44262. this.inspector.beginCompute( this.backend.getTimestampUID( computeNodes ), computeNodes );
  44263. //
  44264. const backend = this.backend;
  44265. const pipelines = this._pipelines;
  44266. const bindings = this._bindings;
  44267. const nodes = this._nodes;
  44268. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  44269. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  44270. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  44271. }
  44272. backend.beginCompute( computeNodes );
  44273. for ( const computeNode of computeList ) {
  44274. // onInit
  44275. if ( pipelines.has( computeNode ) === false ) {
  44276. const dispose = () => {
  44277. computeNode.removeEventListener( 'dispose', dispose );
  44278. pipelines.delete( computeNode );
  44279. bindings.deleteForCompute( computeNode );
  44280. nodes.delete( computeNode );
  44281. };
  44282. computeNode.addEventListener( 'dispose', dispose );
  44283. //
  44284. const onInitFn = computeNode.onInitFunction;
  44285. if ( onInitFn !== null ) {
  44286. onInitFn.call( computeNode, { renderer: this } );
  44287. }
  44288. }
  44289. nodes.updateForCompute( computeNode );
  44290. bindings.updateForCompute( computeNode );
  44291. const computeBindings = bindings.getForCompute( computeNode );
  44292. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  44293. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSize );
  44294. }
  44295. backend.finishCompute( computeNodes );
  44296. //
  44297. nodeFrame.renderId = previousRenderId;
  44298. //
  44299. this.inspector.finishCompute( this.backend.getTimestampUID( computeNodes ) );
  44300. }
  44301. /**
  44302. * Execute a single or an array of compute nodes.
  44303. *
  44304. * @async
  44305. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  44306. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  44307. * - A single number representing count, or
  44308. * - An array [x, y, z] representing dispatch size, or
  44309. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  44310. * @return {Promise} A Promise that resolve when the compute has finished.
  44311. */
  44312. async computeAsync( computeNodes, dispatchSize = null ) {
  44313. if ( this._initialized === false ) await this.init();
  44314. this.compute( computeNodes, dispatchSize );
  44315. }
  44316. /**
  44317. * Checks if the given feature is supported by the selected backend.
  44318. *
  44319. * @async
  44320. * @deprecated
  44321. * @param {string} name - The feature's name.
  44322. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  44323. */
  44324. async hasFeatureAsync( name ) {
  44325. warnOnce( 'Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  44326. await this.init();
  44327. return this.hasFeature( name );
  44328. }
  44329. async resolveTimestampsAsync( type = 'render' ) {
  44330. if ( this._initialized === false ) await this.init();
  44331. return this.backend.resolveTimestampsAsync( type );
  44332. }
  44333. /**
  44334. * Checks if the given feature is supported by the selected backend. If the
  44335. * renderer has not been initialized, this method always returns `false`.
  44336. *
  44337. * @param {string} name - The feature's name.
  44338. * @return {boolean} Whether the feature is supported or not.
  44339. */
  44340. hasFeature( name ) {
  44341. if ( this._initialized === false ) {
  44342. throw new Error( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before using this method.' );
  44343. }
  44344. return this.backend.hasFeature( name );
  44345. }
  44346. /**
  44347. * Returns `true` when the renderer has been initialized.
  44348. *
  44349. * @return {boolean} Whether the renderer has been initialized or not.
  44350. */
  44351. hasInitialized() {
  44352. return this._initialized;
  44353. }
  44354. /**
  44355. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  44356. * (which can cause noticeable lags due to decode and GPU upload overhead).
  44357. *
  44358. * @async
  44359. * @deprecated
  44360. * @param {Texture} texture - The texture.
  44361. * @return {Promise} A Promise that resolves when the texture has been initialized.
  44362. */
  44363. async initTextureAsync( texture ) {
  44364. warnOnce( 'Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  44365. await this.init();
  44366. this.initTexture( texture );
  44367. }
  44368. /**
  44369. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  44370. * (which can cause noticeable lags due to decode and GPU upload overhead).
  44371. *
  44372. * This method can only be used if the renderer has been initialized.
  44373. *
  44374. * @param {Texture} texture - The texture.
  44375. */
  44376. initTexture( texture ) {
  44377. if ( this._initialized === false ) {
  44378. throw new Error( 'THREE.Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before using this method.' );
  44379. }
  44380. this._textures.updateTexture( texture );
  44381. }
  44382. /**
  44383. * Initializes the given render target.
  44384. *
  44385. * @param {RenderTarget} renderTarget - The render target to intialize.
  44386. */
  44387. initRenderTarget( renderTarget ) {
  44388. if ( this._initialized === false ) {
  44389. throw new Error( 'THREE.Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before using this method.' );
  44390. }
  44391. this._textures.updateRenderTarget( renderTarget );
  44392. const renderTargetData = this._textures.get( renderTarget );
  44393. const renderContext = this._renderContexts.get( renderTarget );
  44394. renderContext.textures = renderTargetData.textures;
  44395. renderContext.depthTexture = renderTargetData.depthTexture;
  44396. renderContext.width = renderTargetData.width;
  44397. renderContext.height = renderTargetData.height;
  44398. renderContext.renderTarget = renderTarget;
  44399. renderContext.depth = renderTarget.depthBuffer;
  44400. renderContext.stencil = renderTarget.stencilBuffer;
  44401. this.backend.initRenderTarget( renderContext );
  44402. }
  44403. /**
  44404. * Copies the current bound framebuffer into the given texture.
  44405. *
  44406. * @param {FramebufferTexture} framebufferTexture - The texture.
  44407. * @param {?(Vector2|Vector4)} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  44408. */
  44409. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  44410. if ( rectangle !== null ) {
  44411. if ( rectangle.isVector2 ) {
  44412. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  44413. } else if ( rectangle.isVector4 ) {
  44414. rectangle = _vector4.copy( rectangle ).floor();
  44415. } else {
  44416. error( 'Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  44417. return;
  44418. }
  44419. } else {
  44420. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  44421. }
  44422. //
  44423. let renderContext = this._currentRenderContext;
  44424. let renderTarget;
  44425. if ( renderContext !== null ) {
  44426. renderTarget = renderContext.renderTarget;
  44427. } else {
  44428. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  44429. if ( renderTarget !== null ) {
  44430. this._textures.updateRenderTarget( renderTarget );
  44431. renderContext = this._textures.get( renderTarget );
  44432. }
  44433. }
  44434. //
  44435. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  44436. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  44437. this._inspector.copyFramebufferToTexture( framebufferTexture );
  44438. }
  44439. /**
  44440. * Copies data of the given source texture into a destination texture.
  44441. *
  44442. * @param {Texture} srcTexture - The source texture.
  44443. * @param {Texture} dstTexture - The destination texture.
  44444. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  44445. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  44446. * @param {number} [srcLevel=0] - The source mip level to copy from.
  44447. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  44448. */
  44449. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  44450. this._textures.updateTexture( srcTexture );
  44451. this._textures.updateTexture( dstTexture );
  44452. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  44453. this._inspector.copyTextureToTexture( srcTexture, dstTexture );
  44454. }
  44455. /**
  44456. * Reads pixel data from the given render target.
  44457. *
  44458. * @async
  44459. * @param {RenderTarget} renderTarget - The render target to read from.
  44460. * @param {number} x - The `x` coordinate of the copy region's origin.
  44461. * @param {number} y - The `y` coordinate of the copy region's origin.
  44462. * @param {number} width - The width of the copy region.
  44463. * @param {number} height - The height of the copy region.
  44464. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  44465. * @param {number} [faceIndex=0] - The active cube face index.
  44466. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  44467. */
  44468. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  44469. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  44470. }
  44471. /**
  44472. * Analyzes the given 3D object's hierarchy and builds render lists from the
  44473. * processed hierarchy.
  44474. *
  44475. * @private
  44476. * @param {Object3D} object - The 3D object to process (usually a scene).
  44477. * @param {Camera} camera - The camera the object is rendered with.
  44478. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  44479. * @param {RenderList} renderList - The current render list.
  44480. * @param {ClippingContext} clippingContext - The current clipping context.
  44481. */
  44482. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  44483. if ( object.visible === false ) return;
  44484. const visible = object.layers.test( camera.layers );
  44485. if ( visible ) {
  44486. if ( object.isGroup ) {
  44487. groupOrder = object.renderOrder;
  44488. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  44489. } else if ( object.isLOD ) {
  44490. if ( object.autoUpdate === true ) object.update( camera );
  44491. } else if ( object.isLight ) {
  44492. renderList.pushLight( object );
  44493. } else if ( object.isSprite ) {
  44494. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  44495. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  44496. if ( this.sortObjects === true ) {
  44497. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  44498. }
  44499. const { geometry, material } = object;
  44500. if ( material.visible ) {
  44501. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  44502. }
  44503. }
  44504. } else if ( object.isLineLoop ) {
  44505. error( 'Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  44506. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  44507. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  44508. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  44509. const { geometry, material } = object;
  44510. if ( this.sortObjects === true ) {
  44511. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  44512. _vector4
  44513. .copy( geometry.boundingSphere.center )
  44514. .applyMatrix4( object.matrixWorld )
  44515. .applyMatrix4( _projScreenMatrix );
  44516. }
  44517. if ( Array.isArray( material ) ) {
  44518. const groups = geometry.groups;
  44519. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  44520. const group = groups[ i ];
  44521. const groupMaterial = material[ group.materialIndex ];
  44522. if ( groupMaterial && groupMaterial.visible ) {
  44523. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  44524. }
  44525. }
  44526. } else if ( material.visible ) {
  44527. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  44528. }
  44529. }
  44530. }
  44531. }
  44532. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  44533. const baseRenderList = renderList;
  44534. // replace render list
  44535. renderList = this._renderLists.get( object, camera );
  44536. renderList.begin();
  44537. baseRenderList.pushBundle( {
  44538. bundleGroup: object,
  44539. camera,
  44540. renderList,
  44541. } );
  44542. renderList.finish();
  44543. }
  44544. const children = object.children;
  44545. for ( let i = 0, l = children.length; i < l; i ++ ) {
  44546. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  44547. }
  44548. }
  44549. /**
  44550. * Renders the given render bundles.
  44551. *
  44552. * @private
  44553. * @param {Array<Object>} bundles - Array with render bundle data.
  44554. * @param {Scene} sceneRef - The scene the render bundles belong to.
  44555. * @param {LightsNode} lightsNode - The current lights node.
  44556. */
  44557. _renderBundles( bundles, sceneRef, lightsNode ) {
  44558. for ( const bundle of bundles ) {
  44559. this._renderBundle( bundle, sceneRef, lightsNode );
  44560. }
  44561. }
  44562. /**
  44563. * Renders the transparent objects from the given render lists.
  44564. *
  44565. * @private
  44566. * @param {Array<Object>} renderList - The transparent render list.
  44567. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  44568. * @param {Camera} camera - The camera the render list should be rendered with.
  44569. * @param {Scene} scene - The scene the render list belongs to.
  44570. * @param {LightsNode} lightsNode - The current lights node.
  44571. */
  44572. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  44573. if ( doublePassList.length > 0 ) {
  44574. // render back side
  44575. for ( const { material } of doublePassList ) {
  44576. material.side = BackSide;
  44577. }
  44578. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  44579. // render front side
  44580. for ( const { material } of doublePassList ) {
  44581. material.side = FrontSide;
  44582. }
  44583. this._renderObjects( renderList, camera, scene, lightsNode );
  44584. // restore
  44585. for ( const { material } of doublePassList ) {
  44586. material.side = DoubleSide;
  44587. }
  44588. } else {
  44589. this._renderObjects( renderList, camera, scene, lightsNode );
  44590. }
  44591. }
  44592. /**
  44593. * Renders the objects from the given render list.
  44594. *
  44595. * @private
  44596. * @param {Array<Object>} renderList - The render list.
  44597. * @param {Camera} camera - The camera the render list should be rendered with.
  44598. * @param {Scene} scene - The scene the render list belongs to.
  44599. * @param {LightsNode} lightsNode - The current lights node.
  44600. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  44601. */
  44602. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  44603. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  44604. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  44605. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  44606. }
  44607. }
  44608. /**
  44609. * Retrieves shadow nodes for the given material. This is used to setup shadow passes.
  44610. * The result is cached per material and updated when the material's version changes.
  44611. *
  44612. * @private
  44613. * @param {Material} material
  44614. * @returns {Object} - The shadow nodes for the material.
  44615. */
  44616. _getShadowNodes( material ) {
  44617. const version = material.version;
  44618. let cache = this._cacheShadowNodes.get( material );
  44619. if ( cache === undefined || cache.version !== version ) {
  44620. const hasMap = material.map !== null;
  44621. const hasColorNode = material.colorNode && material.colorNode.isNode;
  44622. const hasCastShadowNode = material.castShadowNode && material.castShadowNode.isNode;
  44623. const hasMaskNode = ( material.maskShadowNode && material.maskShadowNode.isNode ) || ( material.maskNode && material.maskNode.isNode );
  44624. let positionNode = null;
  44625. let colorNode = null;
  44626. let depthNode = null;
  44627. if ( hasMap || hasColorNode || hasCastShadowNode || hasMaskNode ) {
  44628. let shadowRGB;
  44629. let shadowAlpha;
  44630. if ( hasCastShadowNode ) {
  44631. shadowRGB = material.castShadowNode.rgb;
  44632. shadowAlpha = material.castShadowNode.a;
  44633. if ( this.shadowMap.transmitted !== true ) {
  44634. warnOnce( 'Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.' );
  44635. }
  44636. } else {
  44637. shadowRGB = vec3( 0 );
  44638. shadowAlpha = float( 1 );
  44639. }
  44640. if ( hasMap ) {
  44641. shadowAlpha = shadowAlpha.mul( reference( 'map', 'texture', material ).a );
  44642. }
  44643. if ( hasColorNode ) {
  44644. shadowAlpha = shadowAlpha.mul( material.colorNode.a );
  44645. }
  44646. colorNode = vec4( shadowRGB, shadowAlpha );
  44647. if ( hasMaskNode ) {
  44648. const maskNode = material.maskShadowNode || material.maskNode;
  44649. colorNode = Fn( ( [ color ] ) => {
  44650. maskNode.not().discard();
  44651. return color;
  44652. } )( colorNode );
  44653. }
  44654. }
  44655. if ( material.depthNode && material.depthNode.isNode ) {
  44656. depthNode = material.depthNode;
  44657. }
  44658. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  44659. positionNode = material.castShadowPositionNode;
  44660. } else if ( material.positionNode && material.positionNode.isNode ) {
  44661. positionNode = material.positionNode;
  44662. }
  44663. cache = {
  44664. version,
  44665. colorNode,
  44666. depthNode,
  44667. positionNode
  44668. };
  44669. this._cacheShadowNodes.set( material, cache );
  44670. }
  44671. return cache;
  44672. }
  44673. /**
  44674. * Updates the camera so it's prepared for rendering operations.
  44675. *
  44676. * @private
  44677. * @param {Camera} camera - The camera to update.
  44678. * @return {Camera} The returned camera might be different depending on whether XR is used or not.
  44679. */
  44680. _updateCamera( camera ) {
  44681. const xr = this.xr;
  44682. if ( xr.isPresenting === false ) {
  44683. let projectionMatrixNeedsUpdate = false;
  44684. // reversed depth
  44685. if ( this.reversedDepthBuffer === true && camera.reversedDepth !== true ) {
  44686. camera._reversedDepth = true;
  44687. if ( camera.isArrayCamera ) {
  44688. for ( const subCamera of camera.cameras ) {
  44689. subCamera._reversedDepth = true;
  44690. }
  44691. }
  44692. projectionMatrixNeedsUpdate = true;
  44693. }
  44694. // WebGPU/WebGL coordinate system
  44695. const coordinateSystem = this.coordinateSystem;
  44696. if ( camera.coordinateSystem !== coordinateSystem ) {
  44697. camera.coordinateSystem = coordinateSystem;
  44698. if ( camera.isArrayCamera ) {
  44699. for ( const subCamera of camera.cameras ) {
  44700. subCamera.coordinateSystem = coordinateSystem;
  44701. }
  44702. }
  44703. projectionMatrixNeedsUpdate = true;
  44704. }
  44705. // camera update
  44706. if ( projectionMatrixNeedsUpdate === true ) {
  44707. camera.updateProjectionMatrix();
  44708. if ( camera.isArrayCamera ) {
  44709. for ( const subCamera of camera.cameras ) {
  44710. subCamera.updateProjectionMatrix();
  44711. }
  44712. }
  44713. }
  44714. }
  44715. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  44716. // handle XR
  44717. if ( xr.enabled === true && xr.isPresenting === true ) {
  44718. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  44719. camera = xr.getCamera(); // use XR camera for rendering
  44720. }
  44721. return camera;
  44722. }
  44723. /**
  44724. * This method represents the default render object function that manages the render lifecycle
  44725. * of the object.
  44726. *
  44727. * @param {Object3D} object - The 3D object.
  44728. * @param {Scene} scene - The scene the 3D object belongs to.
  44729. * @param {Camera} camera - The camera the object should be rendered with.
  44730. * @param {BufferGeometry} geometry - The object's geometry.
  44731. * @param {Material} material - The object's material.
  44732. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  44733. * @param {LightsNode} lightsNode - The current lights node.
  44734. * @param {?ClippingContext} clippingContext - The clipping context.
  44735. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  44736. */
  44737. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  44738. let materialOverride = false;
  44739. let materialColorNode;
  44740. let materialDepthNode;
  44741. let materialPositionNode;
  44742. let materialSide;
  44743. let materialDisplacementMap;
  44744. let materialDisplacementScale;
  44745. let materialDisplacementBias;
  44746. const previousSourceMaterial = this._currentSourceMaterial;
  44747. //
  44748. object.onBeforeRender( this, scene, camera, geometry, material, group );
  44749. //
  44750. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  44751. this._currentSourceMaterial = material;
  44752. const overrideMaterial = scene.overrideMaterial;
  44753. materialOverride = true;
  44754. // store original nodes
  44755. materialColorNode = ( overrideMaterial.isNodeMaterial ) ? overrideMaterial.colorNode : null;
  44756. materialDepthNode = ( overrideMaterial.isNodeMaterial ) ? overrideMaterial.depthNode : null;
  44757. materialPositionNode = ( overrideMaterial.isNodeMaterial ) ? overrideMaterial.positionNode : null;
  44758. materialSide = scene.overrideMaterial.side;
  44759. materialDisplacementMap = overrideMaterial.displacementMap;
  44760. materialDisplacementScale = overrideMaterial.displacementScale;
  44761. materialDisplacementBias = overrideMaterial.displacementBias;
  44762. if ( material.positionNode && material.positionNode.isNode ) {
  44763. overrideMaterial.positionNode = material.positionNode;
  44764. }
  44765. overrideMaterial.alphaTest = material.alphaTest;
  44766. overrideMaterial.alphaMap = material.alphaMap;
  44767. overrideMaterial.displacementMap = material.displacementMap;
  44768. overrideMaterial.displacementScale = material.displacementScale;
  44769. overrideMaterial.displacementBias = material.displacementBias;
  44770. overrideMaterial.transparent = material.transparent || material.transmission > 0 ||
  44771. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  44772. ( material.backdropNode && material.backdropNode.isNode );
  44773. if ( overrideMaterial.isShadowPassMaterial ) {
  44774. const { colorNode, depthNode, positionNode } = this._getShadowNodes( material );
  44775. if ( this.shadowMap.type === VSMShadowMap ) {
  44776. overrideMaterial.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  44777. } else {
  44778. overrideMaterial.side = ( material.shadowSide !== null ) ? material.shadowSide : _shadowSide[ material.side ];
  44779. }
  44780. if ( colorNode !== null ) overrideMaterial.colorNode = colorNode;
  44781. if ( depthNode !== null ) overrideMaterial.depthNode = depthNode;
  44782. if ( positionNode !== null ) overrideMaterial.positionNode = positionNode;
  44783. }
  44784. material = overrideMaterial;
  44785. }
  44786. //
  44787. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  44788. material.side = BackSide;
  44789. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  44790. material.side = FrontSide;
  44791. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  44792. material.side = DoubleSide;
  44793. } else {
  44794. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  44795. }
  44796. //
  44797. if ( materialOverride ) {
  44798. scene.overrideMaterial.colorNode = materialColorNode;
  44799. scene.overrideMaterial.depthNode = materialDepthNode;
  44800. scene.overrideMaterial.positionNode = materialPositionNode;
  44801. scene.overrideMaterial.side = materialSide;
  44802. scene.overrideMaterial.displacementMap = materialDisplacementMap;
  44803. scene.overrideMaterial.displacementScale = materialDisplacementScale;
  44804. scene.overrideMaterial.displacementBias = materialDisplacementBias;
  44805. }
  44806. this._currentSourceMaterial = previousSourceMaterial;
  44807. //
  44808. object.onAfterRender( this, scene, camera, geometry, material, group );
  44809. }
  44810. /**
  44811. * Checks if the given compatibility is supported by the selected backend.
  44812. *
  44813. * @param {string} name - The compatibility's name.
  44814. * @return {boolean} Whether the compatibility is supported or not.
  44815. */
  44816. hasCompatibility( name ) {
  44817. if ( this._initialized === false ) {
  44818. throw new Error( 'THREE.Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.' );
  44819. }
  44820. return this.backend.hasCompatibility( name );
  44821. }
  44822. /**
  44823. * This method represents the default `_handleObjectFunction` implementation which creates
  44824. * a render object from the given data and performs the draw command with the selected backend.
  44825. *
  44826. * @private
  44827. * @param {Object3D} object - The 3D object.
  44828. * @param {Material} material - The object's material.
  44829. * @param {Scene} scene - The scene the 3D object belongs to.
  44830. * @param {Camera} camera - The camera the object should be rendered with.
  44831. * @param {LightsNode} lightsNode - The current lights node.
  44832. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  44833. * @param {ClippingContext} clippingContext - The clipping context.
  44834. * @param {string} [passId] - An optional ID for identifying the pass.
  44835. */
  44836. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  44837. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  44838. renderObject.drawRange = object.geometry.drawRange;
  44839. renderObject.group = group;
  44840. if ( this._currentRenderBundle !== null ) {
  44841. const renderBundleData = this.backend.get( this._currentRenderBundle );
  44842. renderBundleData.renderObjects.push( renderObject );
  44843. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  44844. }
  44845. //
  44846. const needsRefresh = this._nodes.needsRefresh( renderObject );
  44847. if ( needsRefresh ) {
  44848. this._nodes.updateBefore( renderObject );
  44849. this._geometries.updateForRender( renderObject );
  44850. this._nodes.updateForRender( renderObject );
  44851. this._bindings.updateForRender( renderObject );
  44852. }
  44853. this._pipelines.updateForRender( renderObject );
  44854. //
  44855. if ( this._pipelines.isReady( renderObject ) ) {
  44856. this.backend.draw( renderObject, this.info );
  44857. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  44858. }
  44859. }
  44860. /**
  44861. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  44862. * Used in `compileAsync()`.
  44863. *
  44864. * @private
  44865. * @param {Object3D} object - The 3D object.
  44866. * @param {Material} material - The object's material.
  44867. * @param {Scene} scene - The scene the 3D object belongs to.
  44868. * @param {Camera} camera - The camera the object should be rendered with.
  44869. * @param {LightsNode} lightsNode - The current lights node.
  44870. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  44871. * @param {ClippingContext} clippingContext - The clipping context.
  44872. * @param {string} [passId] - An optional ID for identifying the pass.
  44873. */
  44874. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  44875. // If in async compilation mode, queue the work for sequential execution
  44876. if ( this._compilationPromises !== null ) {
  44877. // Store work items instead of promises - will be processed sequentially
  44878. this._compilationPromises.push( {
  44879. object,
  44880. material,
  44881. scene,
  44882. camera,
  44883. lightsNode,
  44884. group,
  44885. clippingContext,
  44886. passId,
  44887. renderContext: this._currentRenderContext
  44888. } );
  44889. return;
  44890. }
  44891. // Sync path
  44892. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  44893. renderObject.drawRange = object.geometry.drawRange;
  44894. renderObject.group = group;
  44895. //
  44896. this._nodes.updateBefore( renderObject );
  44897. this._geometries.updateForRender( renderObject );
  44898. this._nodes.updateForRender( renderObject );
  44899. this._bindings.updateForRender( renderObject );
  44900. this._pipelines.getForRender( renderObject, this._compilationPromises );
  44901. this._nodes.updateAfter( renderObject );
  44902. }
  44903. /**
  44904. * Callback when the canvas has been resized.
  44905. *
  44906. * @private
  44907. */
  44908. _onCanvasTargetResize() {
  44909. if ( this._initialized ) this.backend.updateSize();
  44910. }
  44911. /**
  44912. * Alias for `compileAsync()`.
  44913. *
  44914. * @method
  44915. * @param {Object3D} scene - The scene or 3D object to precompile.
  44916. * @param {Camera} camera - The camera that is used to render the scene.
  44917. * @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.
  44918. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  44919. */
  44920. get compile() {
  44921. return this.compileAsync;
  44922. }
  44923. }
  44924. /**
  44925. * A binding represents the connection between a resource (like a texture, sampler
  44926. * or uniform buffer) and the resource definition in a shader stage.
  44927. *
  44928. * This module is an abstract base class for all concrete bindings types.
  44929. *
  44930. * @abstract
  44931. * @private
  44932. */
  44933. class Binding {
  44934. /**
  44935. * Constructs a new binding.
  44936. *
  44937. * @param {string} [name=''] - The binding's name.
  44938. */
  44939. constructor( name = '' ) {
  44940. /**
  44941. * The binding's name.
  44942. *
  44943. * @type {string}
  44944. */
  44945. this.name = name;
  44946. /**
  44947. * A bitmask that defines in what shader stages the
  44948. * binding's resource is accessible.
  44949. *
  44950. * @type {number}
  44951. */
  44952. this.visibility = 0;
  44953. }
  44954. /**
  44955. * Makes sure binding's resource is visible for the given shader stage.
  44956. *
  44957. * @param {number} visibility - The shader stage.
  44958. */
  44959. setVisibility( visibility ) {
  44960. this.visibility |= visibility;
  44961. }
  44962. /**
  44963. * The shader stages in which the binding's resource is visible.
  44964. *
  44965. * @return {number} The visibility bitmask.
  44966. */
  44967. getVisibility() {
  44968. return this.visibility;
  44969. }
  44970. /**
  44971. * Clones the binding.
  44972. *
  44973. * @return {Binding} The cloned binding.
  44974. */
  44975. clone() {
  44976. return Object.assign( new this.constructor(), this );
  44977. }
  44978. }
  44979. /**
  44980. * This function is usually called with the length in bytes of an array buffer.
  44981. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  44982. *
  44983. * @function
  44984. * @param {number} floatLength - The buffer length.
  44985. * @return {number} The padded length.
  44986. */
  44987. function getFloatLength( floatLength ) {
  44988. // ensure chunk size alignment (STD140 layout)
  44989. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  44990. }
  44991. /**
  44992. * Represents a buffer binding type.
  44993. *
  44994. * @private
  44995. * @abstract
  44996. * @augments Binding
  44997. */
  44998. class Buffer extends Binding {
  44999. /**
  45000. * Constructs a new buffer.
  45001. *
  45002. * @param {string} name - The buffer's name.
  45003. * @param {TypedArray} [buffer=null] - The buffer.
  45004. */
  45005. constructor( name, buffer = null ) {
  45006. super( name );
  45007. /**
  45008. * This flag can be used for type testing.
  45009. *
  45010. * @type {boolean}
  45011. * @readonly
  45012. * @default true
  45013. */
  45014. this.isBuffer = true;
  45015. /**
  45016. * The bytes per element.
  45017. *
  45018. * @type {number}
  45019. */
  45020. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  45021. /**
  45022. * A reference to the internal buffer.
  45023. *
  45024. * @private
  45025. * @type {TypedArray}
  45026. */
  45027. this._buffer = buffer;
  45028. /**
  45029. * An array of update ranges.
  45030. *
  45031. * @private
  45032. * @type {Array<{start: number, count: number}>}
  45033. */
  45034. this._updateRanges = [];
  45035. }
  45036. /**
  45037. * The array of update ranges.
  45038. *
  45039. * @type {Array<{start: number, count: number}>}
  45040. */
  45041. get updateRanges() {
  45042. return this._updateRanges;
  45043. }
  45044. /**
  45045. * Adds an update range.
  45046. *
  45047. * @param {number} start - The start index.
  45048. * @param {number} count - The number of elements.
  45049. */
  45050. addUpdateRange( start, count ) {
  45051. this.updateRanges.push( { start, count } );
  45052. }
  45053. /**
  45054. * Clears all update ranges.
  45055. */
  45056. clearUpdateRanges() {
  45057. this.updateRanges.length = 0;
  45058. }
  45059. /**
  45060. * The buffer's byte length.
  45061. *
  45062. * @type {number}
  45063. * @readonly
  45064. */
  45065. get byteLength() {
  45066. return getFloatLength( this._buffer.byteLength );
  45067. }
  45068. /**
  45069. * A reference to the internal buffer.
  45070. *
  45071. * @type {Float32Array}
  45072. * @readonly
  45073. */
  45074. get buffer() {
  45075. return this._buffer;
  45076. }
  45077. /**
  45078. * Updates the binding.
  45079. *
  45080. * @return {boolean} Whether the buffer has been updated and must be
  45081. * uploaded to the GPU.
  45082. */
  45083. update() {
  45084. return true;
  45085. }
  45086. /**
  45087. * Releases the buffer.
  45088. */
  45089. release() {
  45090. this._buffer = null;
  45091. }
  45092. }
  45093. /**
  45094. * Represents a uniform buffer binding type.
  45095. *
  45096. * @private
  45097. * @augments Buffer
  45098. */
  45099. class UniformBuffer extends Buffer {
  45100. /**
  45101. * Constructs a new uniform buffer.
  45102. *
  45103. * @param {string} name - The buffer's name.
  45104. * @param {TypedArray} [buffer=null] - The buffer.
  45105. */
  45106. constructor( name, buffer = null ) {
  45107. super( name, buffer );
  45108. /**
  45109. * This flag can be used for type testing.
  45110. *
  45111. * @type {boolean}
  45112. * @readonly
  45113. * @default true
  45114. */
  45115. this.isUniformBuffer = true;
  45116. }
  45117. }
  45118. let _id$4 = 0;
  45119. /**
  45120. * A special form of uniform buffer binding type.
  45121. * It's buffer value is managed by a node object.
  45122. *
  45123. * @private
  45124. * @augments UniformBuffer
  45125. */
  45126. class NodeUniformBuffer extends UniformBuffer {
  45127. /**
  45128. * Constructs a new node-based uniform buffer.
  45129. *
  45130. * @param {BufferNode} nodeUniform - The uniform buffer node.
  45131. * @param {UniformGroupNode} groupNode - The uniform group node.
  45132. */
  45133. constructor( nodeUniform, groupNode ) {
  45134. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  45135. /**
  45136. * The uniform buffer node.
  45137. *
  45138. * @type {BufferNode}
  45139. */
  45140. this.nodeUniform = nodeUniform;
  45141. /**
  45142. * The uniform group node.
  45143. *
  45144. * @type {UniformGroupNode}
  45145. */
  45146. this.groupNode = groupNode;
  45147. /**
  45148. * This flag can be used for type testing.
  45149. *
  45150. * @type {boolean}
  45151. * @readonly
  45152. * @default true
  45153. */
  45154. this.isNodeUniformBuffer = true;
  45155. }
  45156. /**
  45157. * The array of update ranges.
  45158. *
  45159. * @param {Array<{start: number, count: number}>} value - The update ranges.
  45160. */
  45161. set updateRanges( value ) {
  45162. this.nodeUniform.updateRanges = value;
  45163. }
  45164. /**
  45165. * The array of update ranges.
  45166. *
  45167. * @type {Array<{start: number, count: number}>}
  45168. */
  45169. get updateRanges() {
  45170. return this.nodeUniform.updateRanges;
  45171. }
  45172. /**
  45173. * Adds a range of data in the data array to be updated on the GPU.
  45174. *
  45175. * @param {number} start - Position at which to start update.
  45176. * @param {number} count - The number of components to update.
  45177. */
  45178. addUpdateRange( start, count ) {
  45179. this.nodeUniform.addUpdateRange( start, count );
  45180. }
  45181. /**
  45182. * Clears all update ranges.
  45183. */
  45184. clearUpdateRanges() {
  45185. this.nodeUniform.clearUpdateRanges();
  45186. }
  45187. /**
  45188. * The buffer's byte length.
  45189. *
  45190. * @type {number}
  45191. * @readonly
  45192. */
  45193. get byteLength() {
  45194. return getFloatLength( this.buffer.byteLength );
  45195. }
  45196. /**
  45197. * The uniform buffer.
  45198. *
  45199. * @type {Float32Array}
  45200. */
  45201. get buffer() {
  45202. return this.nodeUniform.value;
  45203. }
  45204. }
  45205. /**
  45206. * This class represents a uniform buffer binding but with
  45207. * an API that allows to maintain individual uniform objects.
  45208. *
  45209. * @private
  45210. * @augments UniformBuffer
  45211. */
  45212. class UniformsGroup extends UniformBuffer {
  45213. /**
  45214. * Constructs a new uniforms group.
  45215. *
  45216. * @param {string} name - The group's name.
  45217. */
  45218. constructor( name ) {
  45219. super( name );
  45220. /**
  45221. * This flag can be used for type testing.
  45222. *
  45223. * @type {boolean}
  45224. * @readonly
  45225. * @default true
  45226. */
  45227. this.isUniformsGroup = true;
  45228. /**
  45229. * An array with the raw uniform values.
  45230. *
  45231. * @private
  45232. * @type {?Array<number>}
  45233. * @default null
  45234. */
  45235. this._values = null;
  45236. /**
  45237. * An array of uniform objects.
  45238. *
  45239. * The order of uniforms in this array must match the order of uniforms in the shader.
  45240. *
  45241. * @type {Array<Uniform>}
  45242. */
  45243. this.uniforms = [];
  45244. /**
  45245. * A cache for the uniform update ranges.
  45246. *
  45247. * @private
  45248. * @type {Map<number, {start: number, count: number}>}
  45249. */
  45250. this._updateRangeCache = new Map();
  45251. /**
  45252. * Uniform indices whose range has already been pushed into `updateRanges`
  45253. * during the current update cycle. Reset on `clearUpdateRanges()`.
  45254. *
  45255. * @private
  45256. * @type {Set<number>}
  45257. */
  45258. this._addedIndices = new Set();
  45259. }
  45260. /**
  45261. * Adds a uniform's update range to this buffer.
  45262. *
  45263. * @param {Uniform} uniform - The uniform.
  45264. */
  45265. addUniformUpdateRange( uniform ) {
  45266. const index = uniform.index;
  45267. if ( this._addedIndices.has( index ) ) return;
  45268. let range = this._updateRangeCache.get( index );
  45269. if ( range === undefined ) {
  45270. range = { start: 0, count: 0 };
  45271. this._updateRangeCache.set( index, range );
  45272. }
  45273. range.start = uniform.offset;
  45274. range.count = uniform.itemSize;
  45275. this._addedIndices.add( index );
  45276. this.updateRanges.push( range );
  45277. }
  45278. /**
  45279. * Clears all update ranges of this buffer.
  45280. */
  45281. clearUpdateRanges() {
  45282. this._addedIndices.clear();
  45283. super.clearUpdateRanges();
  45284. }
  45285. /**
  45286. * Adds a uniform to this group.
  45287. *
  45288. * @param {Uniform} uniform - The uniform to add.
  45289. * @return {UniformsGroup} A reference to this group.
  45290. */
  45291. addUniform( uniform ) {
  45292. this.uniforms.push( uniform );
  45293. return this;
  45294. }
  45295. /**
  45296. * Removes a uniform from this group.
  45297. *
  45298. * @param {Uniform} uniform - The uniform to remove.
  45299. * @return {UniformsGroup} A reference to this group.
  45300. */
  45301. removeUniform( uniform ) {
  45302. const index = this.uniforms.indexOf( uniform );
  45303. if ( index !== -1 ) {
  45304. this.uniforms.splice( index, 1 );
  45305. }
  45306. return this;
  45307. }
  45308. /**
  45309. * An array with the raw uniform values.
  45310. *
  45311. * @type {Array<number>}
  45312. */
  45313. get values() {
  45314. if ( this._values === null ) {
  45315. this._values = Array.from( this.buffer );
  45316. }
  45317. return this._values;
  45318. }
  45319. /**
  45320. * A Float32 array buffer with the uniform values.
  45321. *
  45322. * @type {Float32Array}
  45323. */
  45324. get buffer() {
  45325. let buffer = this._buffer;
  45326. if ( buffer === null ) {
  45327. const byteLength = this.byteLength;
  45328. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  45329. this._buffer = buffer;
  45330. }
  45331. return buffer;
  45332. }
  45333. /**
  45334. * The byte length of the buffer with correct buffer alignment.
  45335. *
  45336. * @type {number}
  45337. */
  45338. get byteLength() {
  45339. const bytesPerElement = this.bytesPerElement;
  45340. let offset = 0; // global buffer offset in bytes
  45341. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  45342. const uniform = this.uniforms[ i ];
  45343. const boundary = uniform.boundary;
  45344. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  45345. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  45346. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  45347. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  45348. offset += chunkPadding;
  45349. // Check for chunk overflow
  45350. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  45351. // Add padding to the end of the chunk
  45352. offset += ( GPU_CHUNK_BYTES - chunkStart );
  45353. }
  45354. uniform.offset = offset / bytesPerElement;
  45355. uniform.index = i;
  45356. offset += itemSize;
  45357. }
  45358. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  45359. }
  45360. /**
  45361. * Updates this group by updating each uniform object of
  45362. * the internal uniform list. The uniform objects check if their
  45363. * values has actually changed so this method only returns
  45364. * `true` if there is a real value change.
  45365. *
  45366. * @return {boolean} Whether the uniforms have been updated and
  45367. * must be uploaded to the GPU.
  45368. */
  45369. update() {
  45370. let updated = false;
  45371. for ( const uniform of this.uniforms ) {
  45372. if ( this.updateByType( uniform ) === true ) {
  45373. updated = true;
  45374. }
  45375. }
  45376. return updated;
  45377. }
  45378. /**
  45379. * Releases the buffer.
  45380. */
  45381. release() {
  45382. super.release();
  45383. this._values = null;
  45384. }
  45385. /**
  45386. * Updates a given uniform by calling an update method matching
  45387. * the uniforms type.
  45388. *
  45389. * @param {Uniform} uniform - The uniform to update.
  45390. * @return {boolean} Whether the uniform has been updated or not.
  45391. */
  45392. updateByType( uniform ) {
  45393. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  45394. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  45395. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  45396. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  45397. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  45398. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  45399. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  45400. error( 'WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  45401. }
  45402. /**
  45403. * Updates a given Number uniform.
  45404. *
  45405. * @param {NumberUniform} uniform - The Number uniform.
  45406. * @return {boolean} Whether the uniform has been updated or not.
  45407. */
  45408. updateNumber( uniform ) {
  45409. let updated = false;
  45410. const a = this.values;
  45411. const v = uniform.getValue();
  45412. const offset = uniform.offset;
  45413. const type = uniform.getType();
  45414. if ( a[ offset ] !== v ) {
  45415. const b = this._getBufferForType( type );
  45416. b[ offset ] = a[ offset ] = v;
  45417. updated = true;
  45418. this.addUniformUpdateRange( uniform );
  45419. }
  45420. return updated;
  45421. }
  45422. /**
  45423. * Updates a given Vector2 uniform.
  45424. *
  45425. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  45426. * @return {boolean} Whether the uniform has been updated or not.
  45427. */
  45428. updateVector2( uniform ) {
  45429. let updated = false;
  45430. const a = this.values;
  45431. const v = uniform.getValue();
  45432. const offset = uniform.offset;
  45433. const type = uniform.getType();
  45434. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  45435. const b = this._getBufferForType( type );
  45436. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  45437. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  45438. updated = true;
  45439. this.addUniformUpdateRange( uniform );
  45440. }
  45441. return updated;
  45442. }
  45443. /**
  45444. * Updates a given Vector3 uniform.
  45445. *
  45446. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  45447. * @return {boolean} Whether the uniform has been updated or not.
  45448. */
  45449. updateVector3( uniform ) {
  45450. let updated = false;
  45451. const a = this.values;
  45452. const v = uniform.getValue();
  45453. const offset = uniform.offset;
  45454. const type = uniform.getType();
  45455. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  45456. const b = this._getBufferForType( type );
  45457. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  45458. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  45459. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  45460. updated = true;
  45461. this.addUniformUpdateRange( uniform );
  45462. }
  45463. return updated;
  45464. }
  45465. /**
  45466. * Updates a given Vector4 uniform.
  45467. *
  45468. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  45469. * @return {boolean} Whether the uniform has been updated or not.
  45470. */
  45471. updateVector4( uniform ) {
  45472. let updated = false;
  45473. const a = this.values;
  45474. const v = uniform.getValue();
  45475. const offset = uniform.offset;
  45476. const type = uniform.getType();
  45477. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 3 ] !== v.w ) {
  45478. const b = this._getBufferForType( type );
  45479. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  45480. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  45481. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  45482. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  45483. updated = true;
  45484. this.addUniformUpdateRange( uniform );
  45485. }
  45486. return updated;
  45487. }
  45488. /**
  45489. * Updates a given Color uniform.
  45490. *
  45491. * @param {ColorUniform} uniform - The Color uniform.
  45492. * @return {boolean} Whether the uniform has been updated or not.
  45493. */
  45494. updateColor( uniform ) {
  45495. let updated = false;
  45496. const a = this.values;
  45497. const c = uniform.getValue();
  45498. const offset = uniform.offset;
  45499. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  45500. const b = this.buffer;
  45501. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  45502. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  45503. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  45504. updated = true;
  45505. this.addUniformUpdateRange( uniform );
  45506. }
  45507. return updated;
  45508. }
  45509. /**
  45510. * Updates a given Matrix3 uniform.
  45511. *
  45512. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  45513. * @return {boolean} Whether the uniform has been updated or not.
  45514. */
  45515. updateMatrix3( uniform ) {
  45516. let updated = false;
  45517. const a = this.values;
  45518. const e = uniform.getValue().elements;
  45519. const offset = uniform.offset;
  45520. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  45521. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  45522. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  45523. const b = this.buffer;
  45524. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  45525. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  45526. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  45527. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  45528. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  45529. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  45530. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  45531. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  45532. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  45533. updated = true;
  45534. this.addUniformUpdateRange( uniform );
  45535. }
  45536. return updated;
  45537. }
  45538. /**
  45539. * Updates a given Matrix4 uniform.
  45540. *
  45541. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  45542. * @return {boolean} Whether the uniform has been updated or not.
  45543. */
  45544. updateMatrix4( uniform ) {
  45545. let updated = false;
  45546. const a = this.values;
  45547. const e = uniform.getValue().elements;
  45548. const offset = uniform.offset;
  45549. if ( arraysEqual( a, e, offset ) === false ) {
  45550. const b = this.buffer;
  45551. b.set( e, offset );
  45552. setArray( a, e, offset );
  45553. updated = true;
  45554. this.addUniformUpdateRange( uniform );
  45555. }
  45556. return updated;
  45557. }
  45558. /**
  45559. * Returns a typed array that matches the given data type.
  45560. *
  45561. * @private
  45562. * @param {string} type - The data type.
  45563. * @return {TypedArray} The typed array.
  45564. */
  45565. _getBufferForType( type ) {
  45566. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  45567. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  45568. return this.buffer;
  45569. }
  45570. }
  45571. /**
  45572. * Sets the values of the second array to the first array.
  45573. *
  45574. * @private
  45575. * @param {TypedArray} a - The first array.
  45576. * @param {TypedArray} b - The second array.
  45577. * @param {number} offset - An index offset for the first array.
  45578. */
  45579. function setArray( a, b, offset ) {
  45580. for ( let i = 0, l = b.length; i < l; i ++ ) {
  45581. a[ offset + i ] = b[ i ];
  45582. }
  45583. }
  45584. /**
  45585. * Returns `true` if the given arrays are equal.
  45586. *
  45587. * @private
  45588. * @param {TypedArray} a - The first array.
  45589. * @param {TypedArray} b - The second array.
  45590. * @param {number} offset - An index offset for the first array.
  45591. * @return {boolean} Whether the given arrays are equal or not.
  45592. */
  45593. function arraysEqual( a, b, offset ) {
  45594. for ( let i = 0, l = b.length; i < l; i ++ ) {
  45595. if ( a[ offset + i ] !== b[ i ] ) return false;
  45596. }
  45597. return true;
  45598. }
  45599. let _id$3 = 0;
  45600. /**
  45601. * A special form of uniforms group that represents
  45602. * the individual uniforms as node-based uniforms.
  45603. *
  45604. * @private
  45605. * @augments UniformsGroup
  45606. */
  45607. class NodeUniformsGroup extends UniformsGroup {
  45608. /**
  45609. * Constructs a new node-based uniforms group.
  45610. *
  45611. * @param {string} name - The group's name.
  45612. * @param {UniformGroupNode} groupNode - The uniform group node.
  45613. */
  45614. constructor( name, groupNode ) {
  45615. super( name );
  45616. /**
  45617. * The group's ID.
  45618. *
  45619. * @type {number}
  45620. */
  45621. this.id = _id$3 ++;
  45622. /**
  45623. * The uniform group node.
  45624. *
  45625. * @type {UniformGroupNode}
  45626. */
  45627. this.groupNode = groupNode;
  45628. /**
  45629. * This flag can be used for type testing.
  45630. *
  45631. * @type {boolean}
  45632. * @readonly
  45633. * @default true
  45634. */
  45635. this.isNodeUniformsGroup = true;
  45636. }
  45637. }
  45638. /**
  45639. * Represents a sampler binding type.
  45640. *
  45641. * @private
  45642. * @augments Binding
  45643. */
  45644. class Sampler extends Binding {
  45645. /**
  45646. * Constructs a new sampler.
  45647. *
  45648. * @param {string} name - The samplers's name.
  45649. * @param {?Texture} texture - The texture this binding is referring to.
  45650. */
  45651. constructor( name, texture ) {
  45652. super( name );
  45653. /**
  45654. * The texture the sampler is referring to.
  45655. *
  45656. * @private
  45657. * @type {?Texture}
  45658. */
  45659. this._texture = texture;
  45660. /**
  45661. * The binding's version.
  45662. *
  45663. * @type {number}
  45664. */
  45665. this.version = -1;
  45666. /**
  45667. * The binding's generation which is an additional version
  45668. * qualifier.
  45669. *
  45670. * @type {?number}
  45671. * @default null
  45672. */
  45673. this.generation = null;
  45674. /**
  45675. * The binding's sampler key.
  45676. *
  45677. * @type {string}
  45678. * @default ''
  45679. */
  45680. this.samplerKey = '';
  45681. /**
  45682. * This flag can be used for type testing.
  45683. *
  45684. * @type {boolean}
  45685. * @readonly
  45686. * @default true
  45687. */
  45688. this.isSampler = true;
  45689. }
  45690. /**
  45691. * Sets the texture of this sampler.
  45692. *
  45693. * @param {Texture} value - The texture to set.
  45694. */
  45695. set texture( value ) {
  45696. if ( this._texture === value ) return;
  45697. this._texture = value;
  45698. this.reset();
  45699. }
  45700. /**
  45701. * Gets the texture of this sampler.
  45702. * @return {?Texture} The texture.
  45703. */
  45704. get texture() {
  45705. return this._texture;
  45706. }
  45707. /**
  45708. * Updates the binding.
  45709. *
  45710. * @return {boolean} Whether the texture has been updated and must be
  45711. * uploaded to the GPU.
  45712. */
  45713. update() {
  45714. const { texture, version } = this;
  45715. if ( version !== texture.version ) {
  45716. this.version = texture.version;
  45717. return true;
  45718. }
  45719. return false;
  45720. }
  45721. /**
  45722. * Resets the version and generation. This is used when the texture
  45723. * the binding is pointing to is disposed or exchanged.
  45724. */
  45725. reset() {
  45726. this.generation = null;
  45727. this.version = -1;
  45728. }
  45729. /**
  45730. * Releases the texture reference.
  45731. */
  45732. release() {
  45733. this._texture = null;
  45734. }
  45735. }
  45736. let _id$2 = 0;
  45737. /**
  45738. * Represents a sampled texture binding type.
  45739. *
  45740. * @private
  45741. * @augments Sampler
  45742. */
  45743. class SampledTexture extends Sampler {
  45744. /**
  45745. * Constructs a new sampled texture.
  45746. *
  45747. * @param {string} name - The sampled texture's name.
  45748. * @param {?Texture} texture - The texture this binding is referring to.
  45749. */
  45750. constructor( name, texture ) {
  45751. super( name, texture );
  45752. /**
  45753. * This identifier.
  45754. *
  45755. * @type {number}
  45756. */
  45757. this.id = _id$2 ++;
  45758. /**
  45759. * Whether the texture is a storage texture or not.
  45760. *
  45761. * @type {boolean}
  45762. * @default false
  45763. */
  45764. this.store = false;
  45765. /**
  45766. * The mip level to bind for storage textures.
  45767. *
  45768. * @type {number}
  45769. * @default 0
  45770. */
  45771. this.mipLevel = 0;
  45772. /**
  45773. * This flag can be used for type testing.
  45774. *
  45775. * @type {boolean}
  45776. * @readonly
  45777. * @default true
  45778. */
  45779. this.isSampledTexture = true;
  45780. }
  45781. }
  45782. /**
  45783. * A special form of sampled texture binding type.
  45784. * It's texture value is managed by a node object.
  45785. *
  45786. * @private
  45787. * @augments SampledTexture
  45788. */
  45789. class NodeSampledTexture extends SampledTexture {
  45790. /**
  45791. * Constructs a new node-based sampled texture.
  45792. *
  45793. * @param {string} name - The textures's name.
  45794. * @param {TextureNode} textureNode - The texture node.
  45795. * @param {UniformGroupNode} groupNode - The uniform group node.
  45796. * @param {?string} [access=null] - The access type.
  45797. */
  45798. constructor( name, textureNode, groupNode, access = null ) {
  45799. super( name, textureNode ? textureNode.value : null );
  45800. /**
  45801. * The texture node.
  45802. *
  45803. * @type {TextureNode}
  45804. */
  45805. this.textureNode = textureNode;
  45806. /**
  45807. * The uniform group node.
  45808. *
  45809. * @type {UniformGroupNode}
  45810. */
  45811. this.groupNode = groupNode;
  45812. /**
  45813. * The access type.
  45814. *
  45815. * @type {?string}
  45816. * @default null
  45817. */
  45818. this.access = access;
  45819. }
  45820. /**
  45821. * Updates the binding.
  45822. *
  45823. * @return {boolean} Whether the texture has been updated and must be
  45824. * uploaded to the GPU.
  45825. */
  45826. update() {
  45827. const { textureNode } = this;
  45828. if ( this.texture !== textureNode.value ) {
  45829. this.texture = textureNode.value;
  45830. return true;
  45831. }
  45832. return super.update();
  45833. }
  45834. }
  45835. /**
  45836. * A special form of sampled cube texture binding type.
  45837. * It's texture value is managed by a node object.
  45838. *
  45839. * @private
  45840. * @augments NodeSampledTexture
  45841. */
  45842. class NodeSampledCubeTexture extends NodeSampledTexture {
  45843. /**
  45844. * Constructs a new node-based sampled cube texture.
  45845. *
  45846. * @param {string} name - The textures's name.
  45847. * @param {TextureNode} textureNode - The texture node.
  45848. * @param {UniformGroupNode} groupNode - The uniform group node.
  45849. * @param {?string} [access=null] - The access type.
  45850. */
  45851. constructor( name, textureNode, groupNode, access = null ) {
  45852. super( name, textureNode, groupNode, access );
  45853. /**
  45854. * This flag can be used for type testing.
  45855. *
  45856. * @type {boolean}
  45857. * @readonly
  45858. * @default true
  45859. */
  45860. this.isSampledCubeTexture = true;
  45861. }
  45862. }
  45863. /**
  45864. * A special form of sampled 3D texture binding type.
  45865. * It's texture value is managed by a node object.
  45866. *
  45867. * @private
  45868. * @augments NodeSampledTexture
  45869. */
  45870. class NodeSampledTexture3D extends NodeSampledTexture {
  45871. /**
  45872. * Constructs a new node-based sampled 3D texture.
  45873. *
  45874. * @param {string} name - The textures's name.
  45875. * @param {TextureNode} textureNode - The texture node.
  45876. * @param {UniformGroupNode} groupNode - The uniform group node.
  45877. * @param {?string} [access=null] - The access type.
  45878. */
  45879. constructor( name, textureNode, groupNode, access = null ) {
  45880. super( name, textureNode, groupNode, access );
  45881. /**
  45882. * This flag can be used for type testing.
  45883. *
  45884. * @type {boolean}
  45885. * @readonly
  45886. * @default true
  45887. */
  45888. this.isSampledTexture3D = true;
  45889. }
  45890. }
  45891. const glslPolyfills = {
  45892. bitcast_int_uint: new CodeNode( /* glsl */'uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }' ),
  45893. bitcast_uint_int: new CodeNode( /* glsl */'uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }' ),
  45894. textureGather: new CodeNode( /* glsl */`
  45895. vec4 tsl_textureGather( const int comp, sampler2D map, vec2 coord, ivec2 offset, bool flipY ) {
  45896. if ( flipY ) offset.y = - offset.y;
  45897. vec2 size = vec2( textureSize( map, 0 ) );
  45898. vec2 st = floor( coord * size + vec2( offset ) - 0.5 );
  45899. vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
  45900. vec4 ret = vec4(
  45901. textureLod( map, ij.xw, 0.0 )[ comp ],
  45902. textureLod( map, ij.zw, 0.0 )[ comp ],
  45903. textureLod( map, ij.zy, 0.0 )[ comp ],
  45904. textureLod( map, ij.xy, 0.0 )[ comp ]
  45905. );
  45906. return flipY ? ret.wzyx : ret;
  45907. }
  45908. ` ),
  45909. textureGatherArray: new CodeNode( /* glsl */`
  45910. vec4 tsl_textureGather_array( const int comp, sampler2DArray map, vec3 coord, ivec2 offset, bool flipY ) {
  45911. if ( flipY ) offset.y = - offset.y;
  45912. vec2 size = vec2( textureSize( map, 0 ).xy );
  45913. vec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );
  45914. vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
  45915. vec4 ret = vec4(
  45916. textureLod( map, vec3( ij.xw, coord.z ), 0.0 )[ comp ],
  45917. textureLod( map, vec3( ij.zw, coord.z ), 0.0 )[ comp ],
  45918. textureLod( map, vec3( ij.zy, coord.z ), 0.0 )[ comp ],
  45919. textureLod( map, vec3( ij.xy, coord.z ), 0.0 )[ comp ]
  45920. );
  45921. return flipY ? ret.wzyx : ret;
  45922. }
  45923. ` ),
  45924. textureGatherCompare: new CodeNode( /* glsl */`
  45925. vec4 tsl_textureGatherCompare( sampler2DShadow map, vec2 coord, ivec2 offset, float ref, bool flipY ) {
  45926. if ( flipY ) offset.y = - offset.y;
  45927. vec2 size = vec2( textureSize( map, 0 ) );
  45928. vec2 st = floor( coord * size + vec2( offset ) - 0.5 );
  45929. vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
  45930. vec4 ret = vec4(
  45931. textureLod( map, vec3( ij.xw, ref ), 0.0 ),
  45932. textureLod( map, vec3( ij.zw, ref ), 0.0 ),
  45933. textureLod( map, vec3( ij.zy, ref ), 0.0 ),
  45934. textureLod( map, vec3( ij.xy, ref ), 0.0 )
  45935. );
  45936. return flipY ? ret.wzyx : ret;
  45937. }
  45938. ` ),
  45939. textureGatherCompareArray: new CodeNode( /* glsl */`
  45940. vec4 tsl_textureGatherCompare_array( sampler2DArrayShadow map, vec3 coord, ivec2 offset, float ref, bool flipY ) {
  45941. if ( flipY ) offset.y = - offset.y;
  45942. vec2 size = vec2( textureSize( map, 0 ).xy );
  45943. vec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );
  45944. vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
  45945. vec4 ret = vec4(
  45946. texture( map, vec4( ij.xw, coord.z, ref ) ),
  45947. texture( map, vec4( ij.zw, coord.z, ref ) ),
  45948. texture( map, vec4( ij.zy, coord.z, ref ) ),
  45949. texture( map, vec4( ij.xy, coord.z, ref ) )
  45950. );
  45951. return flipY ? ret.wzyx : ret;
  45952. }
  45953. ` )
  45954. };
  45955. const glslMethods = {
  45956. textureDimensions: 'textureSize',
  45957. equals: 'equal',
  45958. bitcast_float_int: 'floatBitsToInt',
  45959. bitcast_int_float: 'intBitsToFloat',
  45960. bitcast_uint_float: 'uintBitsToFloat',
  45961. bitcast_float_uint: 'floatBitsToUint',
  45962. bitcast_uint_int: 'tsl_bitcast_uint_to_int',
  45963. bitcast_int_uint: 'tsl_bitcast_int_to_uint',
  45964. floatpack_snorm_2x16: 'packSnorm2x16',
  45965. floatpack_unorm_2x16: 'packUnorm2x16',
  45966. floatpack_float16_2x16: 'packHalf2x16',
  45967. floatunpack_snorm_2x16: 'unpackSnorm2x16',
  45968. floatunpack_unorm_2x16: 'unpackUnorm2x16',
  45969. floatunpack_float16_2x16: 'unpackHalf2x16'
  45970. };
  45971. const precisionLib = {
  45972. low: 'lowp',
  45973. medium: 'mediump',
  45974. high: 'highp'
  45975. };
  45976. const supports$1 = {
  45977. swizzleAssign: true,
  45978. storageBuffer: false
  45979. };
  45980. const interpolationTypeMap = {
  45981. perspective: 'smooth',
  45982. linear: 'noperspective'
  45983. };
  45984. const interpolationModeMap = {
  45985. 'centroid': 'centroid'
  45986. };
  45987. const defaultPrecisions = `
  45988. precision highp float;
  45989. precision highp int;
  45990. precision highp sampler2D;
  45991. precision highp sampler3D;
  45992. precision highp samplerCube;
  45993. precision highp sampler2DArray;
  45994. precision highp usampler2D;
  45995. precision highp usampler3D;
  45996. precision highp usamplerCube;
  45997. precision highp usampler2DArray;
  45998. precision highp isampler2D;
  45999. precision highp isampler3D;
  46000. precision highp isamplerCube;
  46001. precision highp isampler2DArray;
  46002. precision highp sampler2DShadow;
  46003. precision highp sampler2DArrayShadow;
  46004. precision highp samplerCubeShadow;
  46005. `;
  46006. /**
  46007. * A node builder targeting GLSL.
  46008. *
  46009. * This module generates GLSL shader code from node materials and also
  46010. * generates the respective bindings and vertex buffer definitions. These
  46011. * data are later used by the renderer to create render and compute pipelines
  46012. * for render objects.
  46013. *
  46014. * @augments NodeBuilder
  46015. */
  46016. class GLSLNodeBuilder extends NodeBuilder {
  46017. /**
  46018. * Constructs a new GLSL node builder renderer.
  46019. *
  46020. * @param {Object3D} object - The 3D object.
  46021. * @param {Renderer} renderer - The renderer.
  46022. */
  46023. constructor( object, renderer ) {
  46024. super( object, renderer, new GLSLNodeParser() );
  46025. /**
  46026. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  46027. * another dictionary which manages UBOs per group ('render','frame','object').
  46028. *
  46029. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  46030. */
  46031. this.uniformGroups = {};
  46032. /**
  46033. * An array that holds objects defining the varying and attribute data in
  46034. * context of Transform Feedback.
  46035. *
  46036. * @type {Array<Object<string,AttributeNode|string>>}
  46037. */
  46038. this.transforms = [];
  46039. /**
  46040. * A dictionary that holds for each shader stage a Map of used extensions.
  46041. *
  46042. * @type {Object<string,Map<string,Object>>}
  46043. */
  46044. this.extensions = {};
  46045. /**
  46046. * A dictionary that holds for each shader stage an Array of used builtins.
  46047. *
  46048. * @type {Object<string,Array<string>>}
  46049. */
  46050. this.builtins = { vertex: [], fragment: [], compute: [] };
  46051. }
  46052. /**
  46053. * Checks if the given texture requires a manual conversion to the working color space.
  46054. *
  46055. * @param {Texture} texture - The texture to check.
  46056. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  46057. */
  46058. needsToWorkingColorSpace( texture ) {
  46059. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  46060. }
  46061. /**
  46062. * Includes the given method name into the current
  46063. * function node.
  46064. *
  46065. * @private
  46066. * @param {string} name - The method name to include.
  46067. * @return {CodeNode} The respective code node.
  46068. */
  46069. _include( name ) {
  46070. const codeNode = glslPolyfills[ name ];
  46071. codeNode.build( this );
  46072. this.addInclude( codeNode );
  46073. return codeNode;
  46074. }
  46075. /**
  46076. * Returns the native shader method name for a given generic name.
  46077. *
  46078. * @param {string} method - The method name to resolve.
  46079. * @return {string} The resolved GLSL method name.
  46080. */
  46081. getMethod( method ) {
  46082. if ( glslPolyfills[ method ] !== undefined ) {
  46083. this._include( method );
  46084. }
  46085. return glslMethods[ method ] || method;
  46086. }
  46087. /**
  46088. * Returns the bitcast method name for a given input and outputType.
  46089. *
  46090. * @param {string} type - The output type to bitcast to.
  46091. * @param {string} inputType - The input type of the.
  46092. * @return {string} The resolved GLSL bitcast invocation.
  46093. */
  46094. getBitcastMethod( type, inputType ) {
  46095. return this.getMethod( `bitcast_${ inputType }_${ type }` );
  46096. }
  46097. /**
  46098. * Returns the float packing method name for a given numeric encoding.
  46099. *
  46100. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  46101. * @returns {string} The resolved GLSL float packing method name.
  46102. */
  46103. getFloatPackingMethod( encoding ) {
  46104. return this.getMethod( `floatpack_${ encoding }_2x16` );
  46105. }
  46106. /**
  46107. * Returns the float unpacking method name for a given numeric encoding.
  46108. *
  46109. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  46110. * @returns {string} The resolved GLSL float unpacking method name.
  46111. */
  46112. getFloatUnpackingMethod( encoding ) {
  46113. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  46114. }
  46115. /**
  46116. * Returns the native snippet for a ternary operation.
  46117. *
  46118. * @param {string} condSnippet - The condition determining which expression gets resolved.
  46119. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  46120. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  46121. * @return {string} The resolved method name.
  46122. */
  46123. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  46124. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  46125. }
  46126. /**
  46127. * Returns the output struct name. Not relevant for GLSL.
  46128. *
  46129. * @return {string}
  46130. */
  46131. getOutputStructName() {
  46132. return '';
  46133. }
  46134. /**
  46135. * Builds the given shader node.
  46136. *
  46137. * @param {ShaderNodeInternal} shaderNode - The shader node.
  46138. * @return {string} The GLSL function code.
  46139. */
  46140. buildFunctionCode( shaderNode ) {
  46141. const layout = shaderNode.layout;
  46142. const flowData = this.flowShaderNode( shaderNode );
  46143. const parameters = [];
  46144. for ( const input of layout.inputs ) {
  46145. parameters.push( this.getType( input.type ) + ' ' + input.name );
  46146. }
  46147. //
  46148. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  46149. ${ flowData.vars }
  46150. ${ flowData.code }
  46151. return ${ flowData.result };
  46152. }`;
  46153. //
  46154. return code;
  46155. }
  46156. /**
  46157. * Setups the Pixel Buffer Object (PBO) for the given storage
  46158. * buffer node.
  46159. *
  46160. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  46161. */
  46162. setupPBO( storageBufferNode ) {
  46163. const attribute = storageBufferNode.value;
  46164. if ( attribute.pbo === undefined ) {
  46165. const originalArray = attribute.array;
  46166. const numElements = attribute.count * attribute.itemSize;
  46167. const { itemSize } = attribute;
  46168. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  46169. let format = isInteger ? RedIntegerFormat : RedFormat;
  46170. if ( itemSize === 2 ) {
  46171. format = isInteger ? RGIntegerFormat : RGFormat;
  46172. } else if ( itemSize === 3 ) {
  46173. format = isInteger ? RGBIntegerFormat : RGBFormat;
  46174. } else if ( itemSize === 4 ) {
  46175. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  46176. }
  46177. const typeMap = {
  46178. Float32Array: FloatType,
  46179. Uint8Array: UnsignedByteType,
  46180. Uint16Array: UnsignedShortType,
  46181. Uint32Array: UnsignedIntType,
  46182. Int8Array: ByteType,
  46183. Int16Array: ShortType,
  46184. Int32Array: IntType,
  46185. Uint8ClampedArray: UnsignedByteType,
  46186. };
  46187. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  46188. let height = Math.ceil( ( numElements / itemSize ) / width );
  46189. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  46190. const newSize = width * height * itemSize;
  46191. const newArray = new originalArray.constructor( newSize );
  46192. newArray.set( originalArray, 0 );
  46193. attribute.array = newArray;
  46194. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  46195. pboTexture.needsUpdate = true;
  46196. pboTexture.isPBOTexture = true;
  46197. const pbo = new TextureNode( pboTexture, null, null );
  46198. pbo.setPrecision( 'high' );
  46199. attribute.pboNode = pbo;
  46200. attribute.pbo = pbo.value;
  46201. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  46202. }
  46203. }
  46204. /**
  46205. * Returns a GLSL snippet that represents the property name of the given node.
  46206. *
  46207. * @param {Node} node - The node.
  46208. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46209. * @return {string} The property name.
  46210. */
  46211. getPropertyName( node, shaderStage = this.shaderStage ) {
  46212. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  46213. return node.name;
  46214. }
  46215. return super.getPropertyName( node, shaderStage );
  46216. }
  46217. /**
  46218. * Setups the Pixel Buffer Object (PBO) for the given storage
  46219. * buffer node.
  46220. *
  46221. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  46222. * @return {string} The property name.
  46223. */
  46224. generatePBO( storageArrayElementNode ) {
  46225. const { node, indexNode } = storageArrayElementNode;
  46226. const attribute = node.value;
  46227. if ( this.renderer.backend.has( attribute ) ) {
  46228. const attributeData = this.renderer.backend.get( attribute );
  46229. attributeData.pbo = attribute.pbo;
  46230. }
  46231. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  46232. const textureName = this.getPropertyName( nodeUniform );
  46233. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  46234. const indexSnippet = indexNode.build( this, 'uint' );
  46235. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  46236. let propertyName = elementNodeData.propertyName;
  46237. if ( propertyName === undefined ) {
  46238. // property element
  46239. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  46240. propertyName = this.getPropertyName( nodeVar );
  46241. // property size
  46242. const bufferNodeData = this.getDataFromNode( node );
  46243. let propertySizeName = bufferNodeData.propertySizeName;
  46244. if ( propertySizeName === undefined ) {
  46245. propertySizeName = propertyName + 'Size';
  46246. this.getVarFromNode( node, propertySizeName, 'uint' );
  46247. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  46248. bufferNodeData.propertySizeName = propertySizeName;
  46249. }
  46250. //
  46251. const { itemSize } = attribute;
  46252. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  46253. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  46254. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, '0', null, null );
  46255. //
  46256. let prefix = 'vec4';
  46257. if ( attribute.pbo.type === UnsignedIntType ) {
  46258. prefix = 'uvec4';
  46259. } else if ( attribute.pbo.type === IntType ) {
  46260. prefix = 'ivec4';
  46261. }
  46262. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  46263. elementNodeData.propertyName = propertyName;
  46264. }
  46265. return propertyName;
  46266. }
  46267. /**
  46268. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  46269. *
  46270. * @param {?Texture} texture - The texture.
  46271. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46272. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  46273. * @param {?string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  46274. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  46275. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  46276. * @return {string} The GLSL snippet.
  46277. */
  46278. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  46279. if ( levelSnippet === null ) levelSnippet = '0';
  46280. let snippet;
  46281. if ( depthSnippet ) {
  46282. if ( offsetSnippet ) {
  46283. snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), int( ${ levelSnippet } ), ${ offsetSnippet } )`;
  46284. } else {
  46285. snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), int( ${ levelSnippet } ) )`;
  46286. }
  46287. } else {
  46288. if ( offsetSnippet ) {
  46289. snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, int( ${ levelSnippet } ), ${ offsetSnippet } )`;
  46290. } else {
  46291. snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, int( ${ levelSnippet } ) )`;
  46292. }
  46293. }
  46294. if ( texture !== null && texture.isDepthTexture ) {
  46295. snippet += '.x';
  46296. }
  46297. return snippet;
  46298. }
  46299. /**
  46300. * Generates the GLSL snippet for sampling/loading the given texture.
  46301. *
  46302. * @param {Texture} texture - The texture.
  46303. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46304. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  46305. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  46306. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  46307. * @return {string} The GLSL snippet.
  46308. */
  46309. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
  46310. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  46311. if ( texture.isDepthTexture ) {
  46312. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
  46313. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  46314. }
  46315. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
  46316. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  46317. }
  46318. /**
  46319. * Generates the GLSL snippet when sampling textures with explicit mip level.
  46320. *
  46321. * @param {Texture} texture - The texture.
  46322. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46323. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  46324. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  46325. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  46326. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  46327. * @return {string} The GLSL snippet.
  46328. */
  46329. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  46330. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  46331. if ( offsetSnippet ) {
  46332. return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  46333. }
  46334. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  46335. }
  46336. /**
  46337. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  46338. *
  46339. * @param {Texture} texture - The texture.
  46340. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46341. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  46342. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  46343. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  46344. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  46345. * @return {string} The GLSL snippet.
  46346. */
  46347. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet ) {
  46348. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  46349. if ( offsetSnippet ) {
  46350. return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
  46351. }
  46352. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  46353. }
  46354. /**
  46355. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  46356. *
  46357. * @param {Texture} texture - The texture.
  46358. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46359. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  46360. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  46361. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  46362. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  46363. * @return {string} The GLSL snippet.
  46364. */
  46365. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet ) {
  46366. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  46367. if ( offsetSnippet ) {
  46368. return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  46369. }
  46370. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  46371. }
  46372. /**
  46373. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  46374. * against a reference value.
  46375. *
  46376. * @param {Texture} texture - The texture.
  46377. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46378. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  46379. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  46380. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  46381. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  46382. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46383. * @return {string} The GLSL snippet.
  46384. */
  46385. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  46386. if ( shaderStage === 'fragment' ) {
  46387. // Cube shadow maps use vec4(direction, compareValue)
  46388. if ( texture.isCubeTexture ) {
  46389. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ compareSnippet } ) )`;
  46390. }
  46391. if ( depthSnippet ) {
  46392. if ( offsetSnippet ) {
  46393. return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  46394. }
  46395. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  46396. }
  46397. if ( offsetSnippet ) {
  46398. return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  46399. }
  46400. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  46401. } else {
  46402. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  46403. }
  46404. }
  46405. /**
  46406. * Generates the GLSL snippet for gathering four texels from the given texture.
  46407. *
  46408. * @param {Texture} texture - The texture.
  46409. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46410. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  46411. * @param {string} gatherSnippet - A GLSL snippet that represents the index of the channel to read.
  46412. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  46413. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  46414. * @param {?string} flipYSnippet - A GLSL snippet that represents the y-flip. Only used for WebGL.
  46415. * @return {string} The GLSL snippet.
  46416. */
  46417. generateTextureGather( texture, textureProperty, uvSnippet, gatherSnippet, depthSnippet, offsetSnippet, flipYSnippet ) {
  46418. if ( texture.isDepthTexture ) gatherSnippet = '0';
  46419. if ( offsetSnippet === null ) offsetSnippet = 'ivec2( 0 )';
  46420. if ( flipYSnippet === null ) flipYSnippet = 'false';
  46421. if ( depthSnippet ) {
  46422. this._include( 'textureGatherArray' );
  46423. return `tsl_textureGather_array( ${gatherSnippet}, ${ textureProperty }, vec3( ${ uvSnippet }, ${ depthSnippet } ), ${ offsetSnippet }, ${ flipYSnippet } )`;
  46424. }
  46425. this._include( 'textureGather' );
  46426. return `tsl_textureGather( ${gatherSnippet}, ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ flipYSnippet } )`;
  46427. }
  46428. /**
  46429. * Generates the GLSL snippet for performing a depth comparison on four texels in the given depth texture.
  46430. *
  46431. * @param {Texture} texture - The texture.
  46432. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46433. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  46434. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  46435. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  46436. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  46437. * @param {?string} flipYSnippet - A GLSL snippet that represents the y-flip. Only used for WebGL.
  46438. * @return {string} The GLSL snippet.
  46439. */
  46440. generateTextureGatherCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, flipYSnippet ) {
  46441. if ( offsetSnippet === null ) offsetSnippet = 'ivec2( 0 )';
  46442. if ( flipYSnippet === null ) flipYSnippet = 'false';
  46443. if ( depthSnippet ) {
  46444. this._include( 'textureGatherCompareArray' );
  46445. return `tsl_textureGatherCompare_array( ${ textureProperty }, vec3( ${ uvSnippet }, ${depthSnippet} ), ${ offsetSnippet }, ${ compareSnippet }, ${ flipYSnippet } )`;
  46446. }
  46447. this._include( 'textureGatherCompare' );
  46448. return `tsl_textureGatherCompare( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ compareSnippet }, ${ flipYSnippet } )`;
  46449. }
  46450. /**
  46451. * Returns the uniforms of the given shader stage as a GLSL string.
  46452. *
  46453. * @param {string} shaderStage - The shader stage.
  46454. * @return {string} The GLSL snippet that defines the uniforms.
  46455. */
  46456. getUniforms( shaderStage ) {
  46457. const uniforms = this.uniforms[ shaderStage ];
  46458. const bindingSnippets = [];
  46459. const uniformGroups = {};
  46460. for ( const uniform of uniforms ) {
  46461. let snippet = null;
  46462. let group = false;
  46463. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  46464. const textureNode = uniform.node;
  46465. const texture = textureNode.value;
  46466. let typePrefix = '';
  46467. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  46468. if ( texture.type === UnsignedIntType ) {
  46469. typePrefix = 'u';
  46470. } else if ( texture.type === IntType ) {
  46471. typePrefix = 'i';
  46472. }
  46473. }
  46474. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  46475. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  46476. } else if ( texture.compareFunction && textureNode.compareNode !== null ) {
  46477. if ( texture.isArrayTexture === true ) {
  46478. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  46479. } else {
  46480. snippet = `sampler2DShadow ${ uniform.name };`;
  46481. }
  46482. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  46483. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  46484. } else {
  46485. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  46486. }
  46487. } else if ( uniform.type === 'cubeTexture' ) {
  46488. snippet = `samplerCube ${ uniform.name };`;
  46489. } else if ( uniform.type === 'cubeDepthTexture' ) {
  46490. const texture = uniform.node.value;
  46491. if ( texture.compareFunction ) {
  46492. snippet = `samplerCubeShadow ${ uniform.name };`;
  46493. } else {
  46494. snippet = `samplerCube ${ uniform.name };`;
  46495. }
  46496. } else if ( uniform.type === 'buffer' ) {
  46497. const bufferNode = uniform.node;
  46498. const bufferType = this.getType( bufferNode.bufferType );
  46499. const bufferCount = bufferNode.bufferCount;
  46500. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  46501. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  46502. } else {
  46503. const groupName = uniform.groupNode.name;
  46504. // Check if this group has already been processed
  46505. if ( uniformGroups[ groupName ] === undefined ) {
  46506. // Get the shared uniform group that contains uniforms from all stages
  46507. const sharedUniformGroup = this.uniformGroups[ groupName ];
  46508. if ( sharedUniformGroup !== undefined ) {
  46509. // Generate snippets for ALL uniforms in this shared group
  46510. const snippets = [];
  46511. for ( const sharedUniform of sharedUniformGroup.uniforms ) {
  46512. const type = sharedUniform.getType();
  46513. const vectorType = this.getVectorType( type );
  46514. const precision = sharedUniform.nodeUniform.node.precision;
  46515. let uniformSnippet = `${ vectorType } ${ sharedUniform.name };`;
  46516. if ( precision !== null ) {
  46517. uniformSnippet = precisionLib[ precision ] + ' ' + uniformSnippet;
  46518. }
  46519. snippets.push( '\t' + uniformSnippet );
  46520. }
  46521. uniformGroups[ groupName ] = snippets;
  46522. }
  46523. }
  46524. group = true;
  46525. }
  46526. if ( ! group ) {
  46527. const precision = uniform.node.precision;
  46528. if ( precision !== null ) {
  46529. snippet = precisionLib[ precision ] + ' ' + snippet;
  46530. }
  46531. snippet = 'uniform ' + snippet;
  46532. bindingSnippets.push( snippet );
  46533. }
  46534. }
  46535. let output = '';
  46536. for ( const name in uniformGroups ) {
  46537. const groupSnippets = uniformGroups[ name ];
  46538. output += this._getGLSLUniformStruct( name, groupSnippets.join( '\n' ) ) + '\n';
  46539. }
  46540. output += bindingSnippets.join( '\n' );
  46541. return output;
  46542. }
  46543. /**
  46544. * Returns the type for a given buffer attribute.
  46545. *
  46546. * @param {BufferAttribute} attribute - The buffer attribute.
  46547. * @return {string} The type.
  46548. */
  46549. getTypeFromAttribute( attribute ) {
  46550. let nodeType = super.getTypeFromAttribute( attribute );
  46551. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  46552. let dataAttribute = attribute;
  46553. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  46554. const array = dataAttribute.array;
  46555. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  46556. nodeType = nodeType.slice( 1 );
  46557. }
  46558. }
  46559. return nodeType;
  46560. }
  46561. /**
  46562. * Returns the shader attributes of the given shader stage as a GLSL string.
  46563. *
  46564. * @param {string} shaderStage - The shader stage.
  46565. * @return {string} The GLSL snippet that defines the shader attributes.
  46566. */
  46567. getAttributes( shaderStage ) {
  46568. let snippet = '';
  46569. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  46570. const attributes = this.getAttributesArray();
  46571. let location = 0;
  46572. for ( const attribute of attributes ) {
  46573. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  46574. }
  46575. }
  46576. return snippet;
  46577. }
  46578. /**
  46579. * Returns the members of the given struct type node as a GLSL string.
  46580. *
  46581. * @param {StructTypeNode} struct - The struct type node.
  46582. * @return {string} The GLSL snippet that defines the struct members.
  46583. */
  46584. getStructMembers( struct ) {
  46585. const snippets = [];
  46586. for ( const member of struct.members ) {
  46587. snippets.push( `\t${ member.type } ${ member.name };` );
  46588. }
  46589. return snippets.join( '\n' );
  46590. }
  46591. /**
  46592. * Returns the structs of the given shader stage as a GLSL string.
  46593. *
  46594. * @param {string} shaderStage - The shader stage.
  46595. * @return {string} The GLSL snippet that defines the structs.
  46596. */
  46597. getStructs( shaderStage ) {
  46598. const snippets = [];
  46599. const structs = this.structs[ shaderStage ];
  46600. const outputSnippet = [];
  46601. for ( const struct of structs ) {
  46602. if ( struct.output ) {
  46603. for ( const member of struct.members ) {
  46604. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  46605. }
  46606. } else {
  46607. let snippet = 'struct ' + struct.name + ' {\n';
  46608. snippet += this.getStructMembers( struct );
  46609. snippet += '\n};\n';
  46610. snippets.push( snippet );
  46611. }
  46612. }
  46613. if ( shaderStage === 'fragment' && outputSnippet.length === 0 ) {
  46614. outputSnippet.push( `layout( location = 0 ) out ${ this.getOutputType() } fragColor;` );
  46615. }
  46616. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  46617. }
  46618. /**
  46619. * Returns the varyings of the given shader stage as a GLSL string.
  46620. *
  46621. * @param {string} shaderStage - The shader stage.
  46622. * @return {string} The GLSL snippet that defines the varyings.
  46623. */
  46624. getVaryings( shaderStage ) {
  46625. let snippet = '';
  46626. const varyings = this.varyings;
  46627. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  46628. for ( const varying of varyings ) {
  46629. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  46630. const type = this.getType( varying.type );
  46631. if ( varying.needsInterpolation ) {
  46632. if ( varying.interpolationType ) {
  46633. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  46634. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  46635. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  46636. } else {
  46637. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  46638. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  46639. }
  46640. } else {
  46641. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  46642. }
  46643. }
  46644. } else if ( shaderStage === 'fragment' ) {
  46645. for ( const varying of varyings ) {
  46646. if ( varying.needsInterpolation ) {
  46647. const type = this.getType( varying.type );
  46648. if ( varying.interpolationType ) {
  46649. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  46650. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  46651. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  46652. } else {
  46653. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  46654. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  46655. }
  46656. }
  46657. }
  46658. }
  46659. for ( const builtin of this.builtins[ shaderStage ] ) {
  46660. snippet += `${builtin};\n`;
  46661. }
  46662. return snippet;
  46663. }
  46664. /**
  46665. * Returns the vertex index builtin.
  46666. *
  46667. * @return {string} The vertex index.
  46668. */
  46669. getVertexIndex() {
  46670. return 'uint( gl_VertexID )';
  46671. }
  46672. /**
  46673. * Contextually returns either the vertex stage instance index builtin
  46674. * or the linearized index of an compute invocation within a grid of workgroups.
  46675. *
  46676. * @return {string} The instance index.
  46677. */
  46678. getInstanceIndex() {
  46679. return 'uint( gl_InstanceID )';
  46680. }
  46681. /**
  46682. * Returns a builtin representing the index of an invocation within its workgroup.
  46683. *
  46684. * @return {string} The invocation local index.
  46685. */
  46686. getInvocationLocalIndex() {
  46687. const workgroupSize = this.object.workgroupSize;
  46688. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  46689. return `uint( gl_InstanceID ) % ${size}u`;
  46690. }
  46691. /**
  46692. * Returns a builtin representing the size of a subgroup within the current shader.
  46693. */
  46694. getSubgroupSize() {
  46695. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node' );
  46696. }
  46697. /**
  46698. * Returns a builtin representing the index of an invocation within its subgroup.
  46699. */
  46700. getInvocationSubgroupIndex() {
  46701. error( 'GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node' );
  46702. }
  46703. /**
  46704. * Returns a builtin representing the index of the current invocation's subgroup within its workgroup.
  46705. */
  46706. getSubgroupIndex() {
  46707. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node' );
  46708. }
  46709. /**
  46710. * Returns the draw index builtin.
  46711. *
  46712. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  46713. */
  46714. getDrawIndex() {
  46715. const extensions = this.renderer.backend.extensions;
  46716. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  46717. return 'uint( gl_DrawID )';
  46718. } else {
  46719. return 'nodeUniformDrawId'; // fallback to uniform
  46720. }
  46721. }
  46722. /**
  46723. * Returns the front facing builtin.
  46724. *
  46725. * @return {string} The front facing builtin.
  46726. */
  46727. getFrontFacing() {
  46728. return 'gl_FrontFacing';
  46729. }
  46730. /**
  46731. * Returns the frag coord builtin.
  46732. *
  46733. * @return {string} The frag coord builtin.
  46734. */
  46735. getFragCoord() {
  46736. return 'gl_FragCoord.xy';
  46737. }
  46738. /**
  46739. * Returns the frag depth builtin.
  46740. *
  46741. * @return {string} The frag depth builtin.
  46742. */
  46743. getFragDepth() {
  46744. return 'gl_FragDepth';
  46745. }
  46746. /**
  46747. * Enables the given extension.
  46748. *
  46749. * @param {string} name - The extension name.
  46750. * @param {string} behavior - The extension behavior.
  46751. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  46752. */
  46753. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  46754. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  46755. if ( map.has( name ) === false ) {
  46756. map.set( name, {
  46757. name,
  46758. behavior
  46759. } );
  46760. }
  46761. }
  46762. /**
  46763. * Returns the enabled extensions of the given shader stage as a GLSL string.
  46764. *
  46765. * @param {string} shaderStage - The shader stage.
  46766. * @return {string} The GLSL snippet that defines the enabled extensions.
  46767. */
  46768. getExtensions( shaderStage ) {
  46769. const snippets = [];
  46770. if ( shaderStage === 'vertex' ) {
  46771. const ext = this.renderer.backend.extensions;
  46772. const isBatchedMesh = this.object.isBatchedMesh;
  46773. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  46774. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  46775. }
  46776. }
  46777. const extensions = this.extensions[ shaderStage ];
  46778. if ( extensions !== undefined ) {
  46779. for ( const { name, behavior } of extensions.values() ) {
  46780. snippets.push( `#extension ${name} : ${behavior}` );
  46781. }
  46782. }
  46783. return snippets.join( '\n' );
  46784. }
  46785. /**
  46786. * Returns the clip distances builtin.
  46787. *
  46788. * @return {string} The clip distances builtin.
  46789. */
  46790. getClipDistance() {
  46791. return 'gl_ClipDistance';
  46792. }
  46793. /**
  46794. * Whether the requested feature is available or not.
  46795. *
  46796. * @param {string} name - The requested feature.
  46797. * @return {boolean} Whether the requested feature is supported or not.
  46798. */
  46799. isAvailable( name ) {
  46800. let result = supports$1[ name ];
  46801. if ( result === undefined ) {
  46802. let extensionName;
  46803. result = false;
  46804. switch ( name ) {
  46805. case 'float32Filterable':
  46806. extensionName = 'OES_texture_float_linear';
  46807. break;
  46808. case 'clipDistance':
  46809. extensionName = 'WEBGL_clip_cull_distance';
  46810. break;
  46811. }
  46812. if ( extensionName !== undefined ) {
  46813. const extensions = this.renderer.backend.extensions;
  46814. if ( extensions.has( extensionName ) ) {
  46815. extensions.get( extensionName );
  46816. result = true;
  46817. }
  46818. }
  46819. supports$1[ name ] = result;
  46820. }
  46821. return result;
  46822. }
  46823. /**
  46824. * Whether to flip texture data along its vertical axis or not.
  46825. *
  46826. * @return {boolean} Returns always `true` in context of GLSL.
  46827. */
  46828. isFlipY() {
  46829. return true;
  46830. }
  46831. /**
  46832. * Enables hardware clipping.
  46833. *
  46834. * @param {string} planeCount - The clipping plane count.
  46835. */
  46836. enableHardwareClipping( planeCount ) {
  46837. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  46838. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  46839. }
  46840. /**
  46841. * Enables multiview.
  46842. */
  46843. enableMultiview() {
  46844. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  46845. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  46846. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  46847. }
  46848. /**
  46849. * Registers a transform in context of Transform Feedback.
  46850. *
  46851. * @param {string} varyingName - The varying name.
  46852. * @param {AttributeNode} attributeNode - The attribute node.
  46853. */
  46854. registerTransform( varyingName, attributeNode ) {
  46855. this.transforms.push( { varyingName, attributeNode } );
  46856. }
  46857. /**
  46858. * Returns the transforms of the given shader stage as a GLSL string.
  46859. *
  46860. * @param {string} shaderStage - The shader stage.
  46861. * @return {string} The GLSL snippet that defines the transforms.
  46862. */
  46863. getTransforms( /* shaderStage */ ) {
  46864. const transforms = this.transforms;
  46865. let snippet = '';
  46866. for ( let i = 0; i < transforms.length; i ++ ) {
  46867. const transform = transforms[ i ];
  46868. const attributeName = this.getPropertyName( transform.attributeNode );
  46869. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  46870. }
  46871. return snippet;
  46872. }
  46873. /**
  46874. * Returns a GLSL struct based on the given name and variables.
  46875. *
  46876. * @private
  46877. * @param {string} name - The struct name.
  46878. * @param {string} vars - The struct variables.
  46879. * @return {string} The GLSL snippet representing a struct.
  46880. */
  46881. _getGLSLUniformStruct( name, vars ) {
  46882. return `
  46883. layout( std140 ) uniform ${name} {
  46884. ${vars}
  46885. };`;
  46886. }
  46887. /**
  46888. * Returns a GLSL vertex shader based on the given shader data.
  46889. *
  46890. * @private
  46891. * @param {Object} shaderData - The shader data.
  46892. * @return {string} The vertex shader.
  46893. */
  46894. _getGLSLVertexCode( shaderData ) {
  46895. return `#version 300 es
  46896. ${ this.getSignature() }
  46897. // extensions
  46898. ${shaderData.extensions}
  46899. // precision
  46900. ${ defaultPrecisions }
  46901. // structs
  46902. ${shaderData.structs}
  46903. // uniforms
  46904. ${shaderData.uniforms}
  46905. // varyings
  46906. ${shaderData.varyings}
  46907. // attributes
  46908. ${shaderData.attributes}
  46909. // vars
  46910. ${shaderData.vars}
  46911. // codes
  46912. ${shaderData.codes}
  46913. void main() {
  46914. // transforms
  46915. ${shaderData.transforms}
  46916. // flow
  46917. ${shaderData.flow}
  46918. gl_PointSize = 1.0;
  46919. }
  46920. `;
  46921. }
  46922. /**
  46923. * Returns a GLSL fragment shader based on the given shader data.
  46924. *
  46925. * @private
  46926. * @param {Object} shaderData - The shader data.
  46927. * @return {string} The vertex shader.
  46928. */
  46929. _getGLSLFragmentCode( shaderData ) {
  46930. return `#version 300 es
  46931. ${ this.getSignature() }
  46932. // extensions
  46933. ${shaderData.extensions}
  46934. // precision
  46935. ${ defaultPrecisions }
  46936. // structs
  46937. ${shaderData.structs}
  46938. // uniforms
  46939. ${shaderData.uniforms}
  46940. // varyings
  46941. ${shaderData.varyings}
  46942. // vars
  46943. ${shaderData.vars}
  46944. // codes
  46945. ${shaderData.codes}
  46946. void main() {
  46947. // flow
  46948. ${shaderData.flow}
  46949. }
  46950. `;
  46951. }
  46952. /**
  46953. * Controls the code build of the shader stages.
  46954. */
  46955. buildCode() {
  46956. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  46957. this.sortBindingGroups();
  46958. for ( const shaderStage in shadersData ) {
  46959. let flow = '// code\n\n';
  46960. flow += this.flowCode[ shaderStage ];
  46961. const flowNodes = this.flowNodes[ shaderStage ];
  46962. const mainNode = flowNodes[ flowNodes.length - 1 ];
  46963. for ( const node of flowNodes ) {
  46964. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  46965. const slotName = node.name;
  46966. if ( slotName ) {
  46967. if ( flow.length > 0 ) flow += '\n';
  46968. flow += `\t// flow -> ${ slotName }\n\t`;
  46969. }
  46970. flow += `${ flowSlotData.code }\n\t`;
  46971. if ( node === mainNode && shaderStage !== 'compute' ) {
  46972. flow += '// result\n\t';
  46973. if ( shaderStage === 'vertex' ) {
  46974. flow += 'gl_Position = ';
  46975. flow += `${ this.format( flowSlotData.result, mainNode.getNodeType( this ), 'vec4' ) };`;
  46976. } else if ( shaderStage === 'fragment' ) {
  46977. if ( ! node.outputNode.isOutputStructNode ) {
  46978. flow += 'fragColor = ';
  46979. flow += `${ this.format( flowSlotData.result, mainNode.getNodeType( this ), this.getOutputType() ) };`;
  46980. }
  46981. }
  46982. }
  46983. }
  46984. const stageData = shadersData[ shaderStage ];
  46985. stageData.extensions = this.getExtensions( shaderStage );
  46986. stageData.uniforms = this.getUniforms( shaderStage );
  46987. stageData.attributes = this.getAttributes( shaderStage );
  46988. stageData.varyings = this.getVaryings( shaderStage );
  46989. stageData.vars = this.getVars( shaderStage, true );
  46990. stageData.structs = this.getStructs( shaderStage );
  46991. stageData.codes = this.getCodes( shaderStage );
  46992. stageData.transforms = this.getTransforms( shaderStage );
  46993. stageData.flow = flow;
  46994. // fallbacks
  46995. if ( shaderStage === 'vertex' ) {
  46996. const ext = this.renderer.backend.extensions;
  46997. if ( this.object.isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) === false ) {
  46998. stageData.uniforms += '\nuniform uint nodeUniformDrawId;\n';
  46999. }
  47000. }
  47001. }
  47002. if ( this.material !== null ) {
  47003. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  47004. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  47005. } else {
  47006. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  47007. }
  47008. }
  47009. /**
  47010. * This method is one of the more important ones since it's responsible
  47011. * for generating a matching binding instance for the given uniform node.
  47012. *
  47013. * These bindings are later used in the renderer to create bind groups
  47014. * and layouts.
  47015. *
  47016. * @param {UniformNode} node - The uniform node.
  47017. * @param {string} type - The node data type.
  47018. * @param {string} shaderStage - The shader stage.
  47019. * @param {?string} [name=null] - An optional uniform name.
  47020. * @return {NodeUniform} The node uniform object.
  47021. */
  47022. getUniformFromNode( node, type, shaderStage, name = null ) {
  47023. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  47024. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  47025. let uniformGPU = nodeData.uniformGPU;
  47026. if ( uniformGPU === undefined ) {
  47027. const group = node.groupNode;
  47028. const groupName = group.name;
  47029. const bindings = this.getBindGroupArray( groupName, shaderStage );
  47030. if ( type === 'texture' ) {
  47031. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  47032. bindings.push( uniformGPU );
  47033. } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
  47034. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  47035. bindings.push( uniformGPU );
  47036. } else if ( type === 'texture3D' ) {
  47037. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  47038. bindings.push( uniformGPU );
  47039. } else if ( type === 'buffer' ) {
  47040. uniformNode.name = `buffer${ node.id }`;
  47041. const sharedData = this.getSharedDataFromNode( node );
  47042. let buffer = sharedData.buffer;
  47043. if ( buffer === undefined ) {
  47044. node.name = `NodeBuffer_${ node.id }`;
  47045. buffer = new NodeUniformBuffer( node, group );
  47046. buffer.name = node.name;
  47047. sharedData.buffer = buffer;
  47048. }
  47049. bindings.push( buffer );
  47050. uniformGPU = buffer;
  47051. } else {
  47052. let uniformsGroup = this.uniformGroups[ groupName ];
  47053. if ( uniformsGroup === undefined ) {
  47054. uniformsGroup = new NodeUniformsGroup( groupName, group );
  47055. this.uniformGroups[ groupName ] = uniformsGroup;
  47056. bindings.push( uniformsGroup );
  47057. } else {
  47058. // Add to bindings for this stage if not already present
  47059. if ( bindings.indexOf( uniformsGroup ) === -1 ) {
  47060. bindings.push( uniformsGroup );
  47061. }
  47062. }
  47063. uniformGPU = this.getNodeUniform( uniformNode, type );
  47064. // Only add uniform if not already present in the group (check by name to avoid duplicates across stages)
  47065. const uniformName = uniformGPU.name;
  47066. const alreadyExists = uniformsGroup.uniforms.some( u => u.name === uniformName );
  47067. if ( ! alreadyExists ) {
  47068. uniformsGroup.addUniform( uniformGPU );
  47069. }
  47070. }
  47071. nodeData.uniformGPU = uniformGPU;
  47072. }
  47073. return uniformNode;
  47074. }
  47075. }
  47076. let _vector2 = null;
  47077. let _color4 = null;
  47078. /**
  47079. * Most of the rendering related logic is implemented in the
  47080. * {@link Renderer} module and related management components.
  47081. * Sometimes it is required though to execute commands which are
  47082. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  47083. * This abstract base class defines an interface that encapsulates
  47084. * all backend-related logic. Derived classes for each backend must
  47085. * implement the interface.
  47086. *
  47087. * @abstract
  47088. */
  47089. class Backend {
  47090. /**
  47091. * Constructs a new backend.
  47092. *
  47093. * @param {Object} parameters - An object holding parameters for the backend.
  47094. */
  47095. constructor( parameters = {} ) {
  47096. /**
  47097. * The parameters of the backend.
  47098. *
  47099. * @type {Object}
  47100. */
  47101. this.parameters = Object.assign( {}, parameters );
  47102. /**
  47103. * This weak map holds backend-specific data of objects
  47104. * like textures, attributes or render targets.
  47105. *
  47106. * @type {WeakMap<Object, Object>}
  47107. */
  47108. this.data = new WeakMap();
  47109. /**
  47110. * A reference to the renderer.
  47111. *
  47112. * @type {?Renderer}
  47113. * @default null
  47114. */
  47115. this.renderer = null;
  47116. /**
  47117. * A reference to the canvas element the renderer is drawing to.
  47118. *
  47119. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  47120. * @default null
  47121. */
  47122. this.domElement = null;
  47123. /**
  47124. * A reference to the timestamp query pool.
  47125. *
  47126. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  47127. */
  47128. this.timestampQueryPool = {
  47129. [ TimestampQuery.RENDER ]: null,
  47130. [ TimestampQuery.COMPUTE ]: null
  47131. };
  47132. /**
  47133. * Whether to track timestamps with a Timestamp Query API or not.
  47134. *
  47135. * @type {boolean}
  47136. * @default false
  47137. */
  47138. this.trackTimestamp = ( parameters.trackTimestamp === true );
  47139. }
  47140. /**
  47141. * Initializes the backend so it is ready for usage. Concrete backends
  47142. * are supposed to implement their rendering context creation and related
  47143. * operations in this method.
  47144. *
  47145. * @async
  47146. * @param {Renderer} renderer - The renderer.
  47147. * @return {Promise} A Promise that resolves when the backend has been initialized.
  47148. */
  47149. async init( renderer ) {
  47150. this.renderer = renderer;
  47151. }
  47152. /**
  47153. * The coordinate system of the backend.
  47154. *
  47155. * @abstract
  47156. * @type {number}
  47157. * @readonly
  47158. */
  47159. get coordinateSystem() {}
  47160. // render context
  47161. /**
  47162. * This method is executed at the beginning of a render call and
  47163. * can be used by the backend to prepare the state for upcoming
  47164. * draw calls.
  47165. *
  47166. * @abstract
  47167. * @param {RenderContext} renderContext - The render context.
  47168. */
  47169. beginRender( /*renderContext*/ ) {}
  47170. /**
  47171. * This method is executed at the end of a render call and
  47172. * can be used by the backend to finalize work after draw
  47173. * calls.
  47174. *
  47175. * @abstract
  47176. * @param {RenderContext} renderContext - The render context.
  47177. */
  47178. finishRender( /*renderContext*/ ) {}
  47179. /**
  47180. * Sets the XR rendering destination.
  47181. *
  47182. * Backends that render directly into XR framebuffers can override this hook.
  47183. *
  47184. * @param {?Object} xrTarget - The XR rendering destination.
  47185. */
  47186. setXRTarget( /*xrTarget*/ ) {}
  47187. /**
  47188. * This method is executed at the beginning of a compute call and
  47189. * can be used by the backend to prepare the state for upcoming
  47190. * compute tasks.
  47191. *
  47192. * @abstract
  47193. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47194. */
  47195. beginCompute( /*computeGroup*/ ) {}
  47196. /**
  47197. * This method is executed at the end of a compute call and
  47198. * can be used by the backend to finalize work after compute
  47199. * tasks.
  47200. *
  47201. * @abstract
  47202. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47203. */
  47204. finishCompute( /*computeGroup*/ ) {}
  47205. // render object
  47206. /**
  47207. * Executes a draw command for the given render object.
  47208. *
  47209. * @abstract
  47210. * @param {RenderObject} renderObject - The render object to draw.
  47211. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  47212. */
  47213. draw( /*renderObject, info*/ ) { }
  47214. // compute node
  47215. /**
  47216. * Executes a compute command for the given compute node.
  47217. *
  47218. * @abstract
  47219. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  47220. * @param {Node} computeNode - The compute node.
  47221. * @param {Array<BindGroup>} bindings - The bindings.
  47222. * @param {ComputePipeline} computePipeline - The compute pipeline.
  47223. */
  47224. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  47225. // program
  47226. /**
  47227. * Creates a shader program from the given programmable stage.
  47228. *
  47229. * @abstract
  47230. * @param {ProgrammableStage} program - The programmable stage.
  47231. */
  47232. createProgram( /*program*/ ) { }
  47233. /**
  47234. * Destroys the shader program of the given programmable stage.
  47235. *
  47236. * @abstract
  47237. * @param {ProgrammableStage} program - The programmable stage.
  47238. */
  47239. destroyProgram( /*program*/ ) { }
  47240. // bindings
  47241. /**
  47242. * Creates bindings from the given bind group definition.
  47243. *
  47244. * @abstract
  47245. * @param {BindGroup} bindGroup - The bind group.
  47246. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47247. * @param {number} cacheIndex - The cache index.
  47248. * @param {number} version - The version.
  47249. */
  47250. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  47251. /**
  47252. * Updates the given bind group definition.
  47253. *
  47254. * @abstract
  47255. * @param {BindGroup} bindGroup - The bind group.
  47256. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47257. * @param {number} cacheIndex - The cache index.
  47258. * @param {number} version - The version.
  47259. */
  47260. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  47261. /**
  47262. * Updates a buffer binding.
  47263. *
  47264. * @abstract
  47265. * @param {Buffer} binding - The buffer binding to update.
  47266. */
  47267. updateBinding( /*binding*/ ) { }
  47268. // pipeline
  47269. /**
  47270. * Creates a render pipeline for the given render object.
  47271. *
  47272. * @abstract
  47273. * @param {RenderObject} renderObject - The render object.
  47274. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  47275. */
  47276. createRenderPipeline( /*renderObject, promises*/ ) { }
  47277. /**
  47278. * Creates a compute pipeline for the given compute node.
  47279. *
  47280. * @abstract
  47281. * @param {ComputePipeline} computePipeline - The compute pipeline.
  47282. * @param {Array<BindGroup>} bindings - The bindings.
  47283. */
  47284. createComputePipeline( /*computePipeline, bindings*/ ) { }
  47285. // cache key
  47286. /**
  47287. * Returns `true` if the render pipeline requires an update.
  47288. *
  47289. * @abstract
  47290. * @param {RenderObject} renderObject - The render object.
  47291. * @return {boolean} Whether the render pipeline requires an update or not.
  47292. */
  47293. needsRenderUpdate( /*renderObject*/ ) { }
  47294. /**
  47295. * Returns a cache key that is used to identify render pipelines.
  47296. *
  47297. * @abstract
  47298. * @param {RenderObject} renderObject - The render object.
  47299. * @return {string} The cache key.
  47300. */
  47301. getRenderCacheKey( /*renderObject*/ ) { }
  47302. // node builder
  47303. /**
  47304. * Returns a node builder for the given render object.
  47305. *
  47306. * @abstract
  47307. * @param {RenderObject} renderObject - The render object.
  47308. * @param {Renderer} renderer - The renderer.
  47309. * @return {NodeBuilder} The node builder.
  47310. */
  47311. createNodeBuilder( /*renderObject, renderer*/ ) { }
  47312. // textures
  47313. /**
  47314. * Updates a GPU sampler for the given texture.
  47315. *
  47316. * @abstract
  47317. * @param {Texture} texture - The texture to update the sampler for.
  47318. * @param {TextureNode} textureNode - The texture node to update the sampler with.
  47319. * @return {string} The current sampler key.
  47320. */
  47321. updateSampler( /*texture, textureNode*/ ) { }
  47322. /**
  47323. * Creates a default texture for the given texture that can be used
  47324. * as a placeholder until the actual texture is ready for usage.
  47325. *
  47326. * @abstract
  47327. * @param {Texture} texture - The texture to create a default texture for.
  47328. */
  47329. createDefaultTexture( /*texture*/ ) { }
  47330. /**
  47331. * Defines a texture on the GPU for the given texture object.
  47332. *
  47333. * @abstract
  47334. * @param {Texture} texture - The texture.
  47335. * @param {Object} [options={}] - Optional configuration parameter.
  47336. */
  47337. createTexture( /*texture, options={}*/ ) { }
  47338. /**
  47339. * Uploads the updated texture data to the GPU.
  47340. *
  47341. * @abstract
  47342. * @param {Texture} texture - The texture.
  47343. * @param {Object} [options={}] - Optional configuration parameter.
  47344. */
  47345. updateTexture( /*texture, options = {}*/ ) { }
  47346. /**
  47347. * Generates mipmaps for the given texture.
  47348. *
  47349. * @abstract
  47350. * @param {Texture} texture - The texture.
  47351. */
  47352. generateMipmaps( /*texture*/ ) { }
  47353. /**
  47354. * Destroys the GPU data for the given texture object.
  47355. *
  47356. * @abstract
  47357. * @param {Texture} texture - The texture.
  47358. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  47359. */
  47360. destroyTexture( /*texture, isDefaultTexture*/ ) { }
  47361. /**
  47362. * Returns texture data as a typed array.
  47363. *
  47364. * @abstract
  47365. * @async
  47366. * @param {Texture} texture - The texture to copy.
  47367. * @param {number} x - The x coordinate of the copy origin.
  47368. * @param {number} y - The y coordinate of the copy origin.
  47369. * @param {number} width - The width of the copy.
  47370. * @param {number} height - The height of the copy.
  47371. * @param {number} faceIndex - The face index.
  47372. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47373. */
  47374. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  47375. /**
  47376. * Copies data of the given source texture to the given destination texture.
  47377. *
  47378. * @abstract
  47379. * @param {Texture} srcTexture - The source texture.
  47380. * @param {Texture} dstTexture - The destination texture.
  47381. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  47382. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  47383. * @param {number} [srcLevel=0] - The source mip level to copy from.
  47384. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  47385. */
  47386. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  47387. /**
  47388. * Copies the current bound framebuffer to the given texture.
  47389. *
  47390. * @abstract
  47391. * @param {Texture} texture - The destination texture.
  47392. * @param {RenderContext} renderContext - The render context.
  47393. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  47394. */
  47395. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  47396. // attributes
  47397. /**
  47398. * Creates the GPU buffer of a shader attribute.
  47399. *
  47400. * @abstract
  47401. * @param {BufferAttribute} attribute - The buffer attribute.
  47402. */
  47403. createAttribute( /*attribute*/ ) { }
  47404. /**
  47405. * Creates the GPU buffer of an indexed shader attribute.
  47406. *
  47407. * @abstract
  47408. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  47409. */
  47410. createIndexAttribute( /*attribute*/ ) { }
  47411. /**
  47412. * Creates the GPU buffer of a storage attribute.
  47413. *
  47414. * @abstract
  47415. * @param {BufferAttribute} attribute - The buffer attribute.
  47416. */
  47417. createStorageAttribute( /*attribute*/ ) { }
  47418. /**
  47419. * Creates a uniform buffer.
  47420. *
  47421. * @abstract
  47422. * @param {Buffer} uniformBuffer - The uniform buffer.
  47423. */
  47424. createUniformBuffer( /*uniformBuffer*/ ) { }
  47425. /**
  47426. * Destroys a uniform buffer.
  47427. *
  47428. * @abstract
  47429. * @param {Buffer} uniformBuffer - The uniform buffer.
  47430. */
  47431. destroyUniformBuffer( /*uniformBuffer*/ ) { }
  47432. /**
  47433. * Updates the GPU buffer of a shader attribute.
  47434. *
  47435. * @abstract
  47436. * @param {BufferAttribute} attribute - The buffer attribute to update.
  47437. */
  47438. updateAttribute( /*attribute*/ ) { }
  47439. /**
  47440. * Destroys the GPU buffer of a shader attribute.
  47441. *
  47442. * @abstract
  47443. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  47444. */
  47445. destroyAttribute( /*attribute*/ ) { }
  47446. // canvas
  47447. /**
  47448. * Returns the backend's rendering context.
  47449. *
  47450. * @abstract
  47451. * @return {Object} The rendering context.
  47452. */
  47453. getContext() { }
  47454. /**
  47455. * Backends can use this method if they have to run
  47456. * logic when the renderer gets resized.
  47457. *
  47458. * @abstract
  47459. */
  47460. updateSize() { }
  47461. /**
  47462. * Updates the viewport with the values from the given render context.
  47463. *
  47464. * @abstract
  47465. * @param {RenderContext} renderContext - The render context.
  47466. */
  47467. updateViewport( /*renderContext*/ ) {}
  47468. // utils
  47469. /**
  47470. * Updates a unique identifier for the given render context that can be used
  47471. * to allocate resources like occlusion queries or timestamp queries.
  47472. *
  47473. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  47474. */
  47475. updateTimeStampUID( abstractRenderContext ) {
  47476. const contextData = this.get( abstractRenderContext );
  47477. const frame = this.renderer.info.frame;
  47478. let prefix;
  47479. if ( abstractRenderContext.isComputeNode === true ) {
  47480. prefix = 'c:' + this.renderer.info.compute.frameCalls;
  47481. } else {
  47482. prefix = 'r:' + this.renderer.info.render.frameCalls;
  47483. }
  47484. contextData.timestampUID = prefix + ':' + abstractRenderContext.id + ':f' + frame;
  47485. }
  47486. /**
  47487. * Returns a unique identifier for the given render context that can be used
  47488. * to allocate resources like occlusion queries or timestamp queries.
  47489. *
  47490. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  47491. * @return {string} The unique identifier.
  47492. */
  47493. getTimestampUID( abstractRenderContext ) {
  47494. return this.get( abstractRenderContext ).timestampUID;
  47495. }
  47496. /**
  47497. * Returns all timestamp frames for the given type.
  47498. *
  47499. * @param {string} type - The type of the time stamp.
  47500. * @return {Array<number>} The timestamp frames.
  47501. */
  47502. getTimestampFrames( type ) {
  47503. const queryPool = this.timestampQueryPool[ type ];
  47504. return queryPool ? queryPool.getTimestampFrames() : [];
  47505. }
  47506. /**
  47507. * Returns the query pool for the given uid.
  47508. *
  47509. * @param {string} uid - The unique identifier.
  47510. * @return {TimestampQueryPool} The query pool.
  47511. */
  47512. _getQueryPool( uid ) {
  47513. const type = uid.startsWith( 'c:' ) ? TimestampQuery.COMPUTE : TimestampQuery.RENDER;
  47514. const queryPool = this.timestampQueryPool[ type ];
  47515. return queryPool;
  47516. }
  47517. /**
  47518. * Returns the timestamp for the given uid.
  47519. *
  47520. * @param {string} uid - The unique identifier.
  47521. * @return {number} The timestamp.
  47522. */
  47523. getTimestamp( uid ) {
  47524. const queryPool = this._getQueryPool( uid );
  47525. return queryPool.getTimestamp( uid );
  47526. }
  47527. /**
  47528. * Whether the backend supports query timestamps or not.
  47529. *
  47530. * @type {boolean}
  47531. * @readonly
  47532. */
  47533. get hasTimestamp() {
  47534. return false;
  47535. }
  47536. /**
  47537. * Returns `true` if a timestamp for the given uid is available.
  47538. *
  47539. * @param {string} uid - The unique identifier.
  47540. * @return {boolean} Whether the timestamp is available or not.
  47541. */
  47542. hasTimestampQuery( uid ) {
  47543. const queryPool = this._getQueryPool( uid );
  47544. return queryPool.hasTimestampQuery( uid );
  47545. }
  47546. /**
  47547. * Returns `true` if the given 3D object is fully occluded by other
  47548. * 3D objects in the scene. Backends must implement this method by using
  47549. * a Occlusion Query API.
  47550. *
  47551. * @abstract
  47552. * @param {RenderContext} renderContext - The render context.
  47553. * @param {Object3D} object - The 3D object to test.
  47554. * @return {boolean} Whether the 3D object is fully occluded or not.
  47555. */
  47556. isOccluded( /*renderContext, object*/ ) {}
  47557. /**
  47558. * Resolves the time stamp for the given render context and type.
  47559. *
  47560. * @async
  47561. * @abstract
  47562. * @param {string} [type='render'] - The type of the time stamp.
  47563. * @return {Promise<number>} A Promise that resolves with the time stamp.
  47564. */
  47565. async resolveTimestampsAsync( type = 'render' ) {
  47566. if ( ! this.trackTimestamp ) {
  47567. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  47568. return;
  47569. }
  47570. const queryPool = this.timestampQueryPool[ type ];
  47571. if ( ! queryPool ) {
  47572. return;
  47573. }
  47574. const duration = await queryPool.resolveQueriesAsync();
  47575. this.renderer.info[ type ].timestamp = duration;
  47576. return duration;
  47577. }
  47578. /**
  47579. * This method performs a readback operation by moving buffer data from
  47580. * a storage buffer attribute from the GPU to the CPU.
  47581. *
  47582. * @async
  47583. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  47584. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  47585. */
  47586. async getArrayBufferAsync( /* attribute */ ) {}
  47587. /**
  47588. * Checks if the given feature is supported by the backend.
  47589. *
  47590. * @async
  47591. * @abstract
  47592. * @param {string} name - The feature's name.
  47593. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  47594. */
  47595. async hasFeatureAsync( /*name*/ ) { }
  47596. /**
  47597. * Checks if the given feature is supported by the backend.
  47598. *
  47599. * @abstract
  47600. * @param {string} name - The feature's name.
  47601. * @return {boolean} Whether the feature is supported or not.
  47602. */
  47603. hasFeature( /*name*/ ) {}
  47604. /**
  47605. * Returns the drawing buffer size.
  47606. *
  47607. * @return {Vector2} The drawing buffer size.
  47608. */
  47609. getDrawingBufferSize() {
  47610. _vector2 = _vector2 || new Vector2();
  47611. return this.renderer.getDrawingBufferSize( _vector2 );
  47612. }
  47613. /**
  47614. * Defines the scissor test.
  47615. *
  47616. * @abstract
  47617. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  47618. */
  47619. setScissorTest( /*boolean*/ ) { }
  47620. /**
  47621. * Returns the clear color and alpha into a single
  47622. * color object.
  47623. *
  47624. * @return {Color4} The clear color.
  47625. */
  47626. getClearColor() {
  47627. const renderer = this.renderer;
  47628. _color4 = _color4 || new Color4();
  47629. renderer.getClearColor( _color4 );
  47630. _color4.getRGB( _color4 );
  47631. return _color4;
  47632. }
  47633. /**
  47634. * Returns the DOM element. If no DOM element exists, the backend
  47635. * creates a new one.
  47636. *
  47637. * @return {HTMLCanvasElement} The DOM element.
  47638. */
  47639. getDomElement() {
  47640. let domElement = this.domElement;
  47641. if ( domElement === null ) {
  47642. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  47643. // OffscreenCanvas does not have setAttribute, see #22811
  47644. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  47645. this.domElement = domElement;
  47646. }
  47647. return domElement;
  47648. }
  47649. /**
  47650. * Checks if the backend has the given compatibility.
  47651. *
  47652. * @abstract
  47653. * @param {string} name - The compatibility.
  47654. * @return {boolean} Whether the backend has the given compatibility or not.
  47655. */
  47656. hasCompatibility( /*name*/ ) {
  47657. return false;
  47658. }
  47659. /**
  47660. * Initializes the render target defined in the given render context.
  47661. *
  47662. * @abstract
  47663. * @param {RenderContext} renderContext - The render context.
  47664. */
  47665. initRenderTarget( /*renderContext*/ ) {}
  47666. /**
  47667. * Sets a dictionary for the given object into the
  47668. * internal data structure.
  47669. *
  47670. * @param {Object} object - The object.
  47671. * @param {Object} value - The dictionary to set.
  47672. */
  47673. set( object, value ) {
  47674. this.data.set( object, value );
  47675. }
  47676. /**
  47677. * Returns the dictionary for the given object.
  47678. *
  47679. * @param {Object} object - The object.
  47680. * @return {Object} The object's dictionary.
  47681. */
  47682. get( object ) {
  47683. let map = this.data.get( object );
  47684. if ( map === undefined ) {
  47685. map = {};
  47686. this.data.set( object, map );
  47687. }
  47688. return map;
  47689. }
  47690. /**
  47691. * Checks if the given object has a dictionary
  47692. * with data defined.
  47693. *
  47694. * @param {Object} object - The object.
  47695. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  47696. */
  47697. has( object ) {
  47698. return this.data.has( object );
  47699. }
  47700. /**
  47701. * Deletes an object from the internal data structure.
  47702. *
  47703. * @param {Object} object - The object to delete.
  47704. */
  47705. delete( object ) {
  47706. this.data.delete( object );
  47707. }
  47708. /**
  47709. * Delete GPU data associated with a bind group.
  47710. *
  47711. * @abstract
  47712. * @param {BindGroup} bindGroup - The bind group.
  47713. */
  47714. deleteBindGroupData( /*bindGroup*/ ) { }
  47715. /**
  47716. * Frees internal resources.
  47717. *
  47718. * @abstract
  47719. */
  47720. dispose() { }
  47721. }
  47722. let _id$1 = 0;
  47723. /**
  47724. * This module is internally used in context of compute shaders.
  47725. * This type of shader is not natively supported in WebGL 2 and
  47726. * thus implemented via Transform Feedback. `DualAttributeData`
  47727. * manages the related data.
  47728. *
  47729. * @private
  47730. */
  47731. class DualAttributeData {
  47732. constructor( attributeData, dualBuffer ) {
  47733. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  47734. this.type = attributeData.type;
  47735. this.bufferType = attributeData.bufferType;
  47736. this.pbo = attributeData.pbo;
  47737. this.byteLength = attributeData.byteLength;
  47738. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  47739. this.version = attributeData.version;
  47740. this.isInteger = attributeData.isInteger;
  47741. this.activeBufferIndex = 0;
  47742. this.baseId = attributeData.id;
  47743. }
  47744. get id() {
  47745. return `${ this.baseId }|${ this.activeBufferIndex }`;
  47746. }
  47747. get bufferGPU() {
  47748. return this.buffers[ this.activeBufferIndex ];
  47749. }
  47750. get transformBuffer() {
  47751. return this.buffers[ this.activeBufferIndex ^ 1 ];
  47752. }
  47753. switchBuffers() {
  47754. this.activeBufferIndex ^= 1;
  47755. }
  47756. }
  47757. /**
  47758. * A WebGL 2 backend utility module for managing shader attributes.
  47759. *
  47760. * @private
  47761. */
  47762. class WebGLAttributeUtils {
  47763. /**
  47764. * Constructs a new utility object.
  47765. *
  47766. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47767. */
  47768. constructor( backend ) {
  47769. /**
  47770. * A reference to the WebGL 2 backend.
  47771. *
  47772. * @type {WebGLBackend}
  47773. */
  47774. this.backend = backend;
  47775. }
  47776. /**
  47777. * Creates the GPU buffer for the given buffer attribute.
  47778. *
  47779. * @param {BufferAttribute} attribute - The buffer attribute.
  47780. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  47781. */
  47782. createAttribute( attribute, bufferType ) {
  47783. const backend = this.backend;
  47784. const { gl } = backend;
  47785. const array = attribute.array;
  47786. const usage = attribute.usage || gl.STATIC_DRAW;
  47787. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  47788. const bufferData = backend.get( bufferAttribute );
  47789. let bufferGPU = bufferData.bufferGPU;
  47790. if ( bufferGPU === undefined ) {
  47791. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  47792. bufferData.bufferGPU = bufferGPU;
  47793. bufferData.bufferType = bufferType;
  47794. bufferData.version = bufferAttribute.version;
  47795. }
  47796. //attribute.onUploadCallback();
  47797. let type;
  47798. if ( array instanceof Float32Array ) {
  47799. type = gl.FLOAT;
  47800. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  47801. type = gl.HALF_FLOAT;
  47802. } else if ( array instanceof Uint16Array ) {
  47803. if ( attribute.isFloat16BufferAttribute ) {
  47804. type = gl.HALF_FLOAT;
  47805. } else {
  47806. type = gl.UNSIGNED_SHORT;
  47807. }
  47808. } else if ( array instanceof Int16Array ) {
  47809. type = gl.SHORT;
  47810. } else if ( array instanceof Uint32Array ) {
  47811. type = gl.UNSIGNED_INT;
  47812. } else if ( array instanceof Int32Array ) {
  47813. type = gl.INT;
  47814. } else if ( array instanceof Int8Array ) {
  47815. type = gl.BYTE;
  47816. } else if ( array instanceof Uint8Array ) {
  47817. type = gl.UNSIGNED_BYTE;
  47818. } else if ( array instanceof Uint8ClampedArray ) {
  47819. type = gl.UNSIGNED_BYTE;
  47820. } else {
  47821. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  47822. }
  47823. let attributeData = {
  47824. bufferGPU,
  47825. bufferType,
  47826. type,
  47827. byteLength: array.byteLength,
  47828. bytesPerElement: array.BYTES_PER_ELEMENT,
  47829. version: attribute.version,
  47830. pbo: attribute.pbo,
  47831. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  47832. id: _id$1 ++
  47833. };
  47834. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  47835. // create buffer for transform feedback use
  47836. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  47837. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  47838. }
  47839. backend.set( attribute, attributeData );
  47840. }
  47841. /**
  47842. * Updates the GPU buffer of the given buffer attribute.
  47843. *
  47844. * @param {BufferAttribute} attribute - The buffer attribute.
  47845. */
  47846. updateAttribute( attribute ) {
  47847. const backend = this.backend;
  47848. const { gl } = backend;
  47849. const array = attribute.array;
  47850. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  47851. const bufferData = backend.get( bufferAttribute );
  47852. const bufferType = bufferData.bufferType;
  47853. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  47854. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  47855. if ( updateRanges.length === 0 ) {
  47856. // Not using update ranges
  47857. gl.bufferSubData( bufferType, 0, array );
  47858. } else {
  47859. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  47860. const range = updateRanges[ i ];
  47861. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  47862. array, range.start, range.count );
  47863. }
  47864. bufferAttribute.clearUpdateRanges();
  47865. }
  47866. gl.bindBuffer( bufferType, null );
  47867. bufferData.version = bufferAttribute.version;
  47868. }
  47869. /**
  47870. * Destroys the GPU buffer of the given buffer attribute.
  47871. *
  47872. * @param {BufferAttribute} attribute - The buffer attribute.
  47873. */
  47874. destroyAttribute( attribute ) {
  47875. const backend = this.backend;
  47876. const { gl } = backend;
  47877. if ( attribute.isInterleavedBufferAttribute ) {
  47878. backend.delete( attribute.data );
  47879. }
  47880. const attributeData = backend.get( attribute );
  47881. gl.deleteBuffer( attributeData.bufferGPU );
  47882. backend.delete( attribute );
  47883. }
  47884. /**
  47885. * This method performs a readback operation by moving buffer data from
  47886. * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can
  47887. * be used to retain and reuse handles to the intermediate buffers and prevent
  47888. * new allocation.
  47889. *
  47890. * @async
  47891. * @param {BufferAttribute} attribute - The storage buffer attribute to read frm.
  47892. * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute.
  47893. * @param {number} offset - The storage buffer attribute.
  47894. * @param {number} count - The offset from which to start reading the
  47895. * @return {Promise<ArrayBuffer|ReadbackBuffer>} A promise that resolves with the buffer data when the data are ready.
  47896. */
  47897. async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) {
  47898. const backend = this.backend;
  47899. const { gl } = backend;
  47900. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  47901. const attributeInfo = backend.get( bufferAttribute );
  47902. const { bufferGPU } = attributeInfo;
  47903. const byteLength = count === -1 ? attributeInfo.byteLength - offset : count;
  47904. // read the data back
  47905. let dstBuffer;
  47906. if ( target === null ) {
  47907. dstBuffer = new Uint8Array( new ArrayBuffer( byteLength ) );
  47908. } else if ( target.isReadbackBuffer ) {
  47909. if ( target._mapped === true ) {
  47910. throw new Error( 'THREE.WebGPURenderer: ReadbackBuffer must be released before being used again.' );
  47911. }
  47912. const releaseCallback = () => {
  47913. target.buffer = null;
  47914. target._mapped = false;
  47915. target.removeEventListener( 'release', releaseCallback );
  47916. target.removeEventListener( 'dispose', releaseCallback );
  47917. };
  47918. target.addEventListener( 'release', releaseCallback );
  47919. target.addEventListener( 'dispose', releaseCallback );
  47920. // WebGL has no concept of a "mapped" data buffer so we create a new buffer, instead.
  47921. dstBuffer = new Uint8Array( new ArrayBuffer( byteLength ) );
  47922. target.buffer = dstBuffer.buffer;
  47923. } else {
  47924. dstBuffer = new Uint8Array( target );
  47925. }
  47926. // Ensure the buffer is bound before reading
  47927. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  47928. gl.getBufferSubData( gl.COPY_READ_BUFFER, offset, dstBuffer );
  47929. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  47930. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  47931. // return the appropriate type
  47932. if ( target && target.isReadbackBuffer ) {
  47933. return target;
  47934. } else {
  47935. return dstBuffer.buffer;
  47936. }
  47937. }
  47938. /**
  47939. * Creates a WebGL buffer with the given data.
  47940. *
  47941. * @private
  47942. * @param {WebGL2RenderingContext} gl - The rendering context.
  47943. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  47944. * @param {TypedArray} array - The array of the buffer attribute.
  47945. * @param {GLenum} usage - The usage.
  47946. * @return {WebGLBuffer} The WebGL buffer.
  47947. */
  47948. _createBuffer( gl, bufferType, array, usage ) {
  47949. const bufferGPU = gl.createBuffer();
  47950. gl.bindBuffer( bufferType, bufferGPU );
  47951. gl.bufferData( bufferType, array, usage );
  47952. gl.bindBuffer( bufferType, null );
  47953. return bufferGPU;
  47954. }
  47955. }
  47956. let equationToGL, factorToGL;
  47957. /**
  47958. * A WebGL 2 backend utility module for managing the WebGL state.
  47959. *
  47960. * The major goal of this module is to reduce the number of state changes
  47961. * by caching the WEbGL state with a series of variables. In this way, the
  47962. * renderer only executes state change commands when necessary which
  47963. * improves the overall performance.
  47964. *
  47965. * @private
  47966. */
  47967. class WebGLState {
  47968. /**
  47969. * Constructs a new utility object.
  47970. *
  47971. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47972. */
  47973. constructor( backend ) {
  47974. /**
  47975. * A reference to the WebGL 2 backend.
  47976. *
  47977. * @type {WebGLBackend}
  47978. */
  47979. this.backend = backend;
  47980. /**
  47981. * A reference to the rendering context.
  47982. *
  47983. * @type {WebGL2RenderingContext}
  47984. */
  47985. this.gl = this.backend.gl;
  47986. // Below properties are intended to cache
  47987. // the WebGL state and are not explicitly
  47988. // documented for convenience reasons.
  47989. this.enabled = {};
  47990. this.parameters = {};
  47991. this.currentFlipSided = null;
  47992. this.currentCullFace = null;
  47993. this.currentProgram = null;
  47994. this.currentBlendingEnabled = false;
  47995. this.currentBlending = null;
  47996. this.currentBlendSrc = null;
  47997. this.currentBlendDst = null;
  47998. this.currentBlendSrcAlpha = null;
  47999. this.currentBlendDstAlpha = null;
  48000. this.currentPremultipledAlpha = null;
  48001. this.currentPolygonOffsetFactor = null;
  48002. this.currentPolygonOffsetUnits = null;
  48003. this.currentColorMask = null;
  48004. this.currentDepthReversed = false;
  48005. this.currentDepthFunc = null;
  48006. this.currentDepthMask = null;
  48007. this.currentStencilFunc = null;
  48008. this.currentStencilRef = null;
  48009. this.currentStencilFuncMask = null;
  48010. this.currentStencilFail = null;
  48011. this.currentStencilZFail = null;
  48012. this.currentStencilZPass = null;
  48013. this.currentStencilMask = null;
  48014. this.currentLineWidth = null;
  48015. this.currentClippingPlanes = 0;
  48016. this.currentVAO = null;
  48017. this.currentIndex = null;
  48018. this.currentBoundFramebuffers = {};
  48019. this.currentDrawbuffers = new WeakMap();
  48020. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  48021. this.currentTextureSlot = null;
  48022. this.currentBoundTextures = {};
  48023. this.currentBoundBufferBases = {};
  48024. this._init();
  48025. }
  48026. /**
  48027. * Inits the state of the utility.
  48028. *
  48029. * @private
  48030. */
  48031. _init() {
  48032. const gl = this.gl;
  48033. // Store only WebGL constants here.
  48034. equationToGL = {
  48035. [ AddEquation ]: gl.FUNC_ADD,
  48036. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  48037. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  48038. };
  48039. factorToGL = {
  48040. [ ZeroFactor ]: gl.ZERO,
  48041. [ OneFactor ]: gl.ONE,
  48042. [ SrcColorFactor ]: gl.SRC_COLOR,
  48043. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  48044. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  48045. [ DstColorFactor ]: gl.DST_COLOR,
  48046. [ DstAlphaFactor ]: gl.DST_ALPHA,
  48047. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  48048. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  48049. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  48050. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  48051. };
  48052. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  48053. const viewportParam = gl.getParameter( gl.VIEWPORT );
  48054. this.currentScissor = new Vector4().fromArray( scissorParam );
  48055. this.currentViewport = new Vector4().fromArray( viewportParam );
  48056. this._tempVec4 = new Vector4();
  48057. }
  48058. /**
  48059. * Enables the given WebGL capability.
  48060. *
  48061. * This method caches the capability state so
  48062. * `gl.enable()` is only called when necessary.
  48063. *
  48064. * @param {GLenum} id - The capability to enable.
  48065. */
  48066. enable( id ) {
  48067. const { enabled } = this;
  48068. if ( enabled[ id ] !== true ) {
  48069. this.gl.enable( id );
  48070. enabled[ id ] = true;
  48071. }
  48072. }
  48073. /**
  48074. * Disables the given WebGL capability.
  48075. *
  48076. * This method caches the capability state so
  48077. * `gl.disable()` is only called when necessary.
  48078. *
  48079. * @param {GLenum} id - The capability to enable.
  48080. */
  48081. disable( id ) {
  48082. const { enabled } = this;
  48083. if ( enabled[ id ] !== false ) {
  48084. this.gl.disable( id );
  48085. enabled[ id ] = false;
  48086. }
  48087. }
  48088. /**
  48089. * Specifies whether polygons are front- or back-facing
  48090. * by setting the winding orientation.
  48091. *
  48092. * This method caches the state so `gl.frontFace()` is only
  48093. * called when necessary.
  48094. *
  48095. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  48096. */
  48097. setFlipSided( flipSided ) {
  48098. if ( this.currentFlipSided !== flipSided ) {
  48099. const { gl } = this;
  48100. if ( flipSided ) {
  48101. gl.frontFace( gl.CW );
  48102. } else {
  48103. gl.frontFace( gl.CCW );
  48104. }
  48105. this.currentFlipSided = flipSided;
  48106. }
  48107. }
  48108. /**
  48109. * Specifies whether or not front- and/or back-facing
  48110. * polygons can be culled.
  48111. *
  48112. * This method caches the state so `gl.cullFace()` is only
  48113. * called when necessary.
  48114. *
  48115. * @param {number} cullFace - Defines which polygons are candidates for culling.
  48116. */
  48117. setCullFace( cullFace ) {
  48118. const { gl } = this;
  48119. if ( cullFace !== CullFaceNone ) {
  48120. this.enable( gl.CULL_FACE );
  48121. if ( cullFace !== this.currentCullFace ) {
  48122. if ( cullFace === CullFaceBack ) {
  48123. gl.cullFace( gl.BACK );
  48124. } else if ( cullFace === CullFaceFront ) {
  48125. gl.cullFace( gl.FRONT );
  48126. } else {
  48127. gl.cullFace( gl.FRONT_AND_BACK );
  48128. }
  48129. }
  48130. } else {
  48131. this.disable( gl.CULL_FACE );
  48132. }
  48133. this.currentCullFace = cullFace;
  48134. }
  48135. /**
  48136. * Specifies the width of line primitives.
  48137. *
  48138. * This method caches the state so `gl.lineWidth()` is only
  48139. * called when necessary.
  48140. *
  48141. * @param {number} width - The line width.
  48142. */
  48143. setLineWidth( width ) {
  48144. const { currentLineWidth, gl } = this;
  48145. if ( width !== currentLineWidth ) {
  48146. gl.lineWidth( width );
  48147. this.currentLineWidth = width;
  48148. }
  48149. }
  48150. setMRTBlending( textures, mrt, material ) {
  48151. const gl = this.gl;
  48152. const drawBuffersIndexedExt = this.backend.drawBuffersIndexedExt;
  48153. if ( ! drawBuffersIndexedExt ) {
  48154. 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.' );
  48155. return;
  48156. }
  48157. for ( let i = 0; i < textures.length; i ++ ) {
  48158. const texture = textures[ i ];
  48159. let blending = null;
  48160. if ( mrt !== null ) {
  48161. const blendMode = mrt.getBlendMode( texture.name );
  48162. if ( blendMode.blending === MaterialBlending ) {
  48163. // use material blending
  48164. blending = material;
  48165. } else if ( blendMode.blending !== NoBlending ) {
  48166. blending = blendMode;
  48167. }
  48168. } else {
  48169. // use material blending
  48170. blending = material;
  48171. }
  48172. if ( blending !== null ) {
  48173. this._setMRTBlendingIndex( i, blending );
  48174. } else {
  48175. // use opaque blending (no blending)
  48176. drawBuffersIndexedExt.blendFuncSeparateiOES( i, gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  48177. }
  48178. }
  48179. }
  48180. /**
  48181. * Applies blending configuration for a specific draw buffer index.
  48182. *
  48183. * @private
  48184. * @param {number} index - The draw buffer index.
  48185. * @param {Object} blending - The blending configuration (material or BlendMode).
  48186. */
  48187. _setMRTBlendingIndex( index, blending ) {
  48188. const { gl } = this;
  48189. const drawBuffersIndexedExt = this.backend.drawBuffersIndexedExt;
  48190. const blendingType = blending.blending;
  48191. const blendSrc = blending.blendSrc;
  48192. const blendDst = blending.blendDst;
  48193. const blendEquation = blending.blendEquation;
  48194. const premultipliedAlpha = blending.premultipliedAlpha;
  48195. if ( blendingType === CustomBlending ) {
  48196. const blendSrcAlpha = blending.blendSrcAlpha !== null ? blending.blendSrcAlpha : blendSrc;
  48197. const blendDstAlpha = blending.blendDstAlpha !== null ? blending.blendDstAlpha : blendDst;
  48198. const blendEquationAlpha = blending.blendEquationAlpha !== null ? blending.blendEquationAlpha : blendEquation;
  48199. drawBuffersIndexedExt.blendEquationSeparateiOES( index, equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  48200. drawBuffersIndexedExt.blendFuncSeparateiOES( index, factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  48201. } else {
  48202. drawBuffersIndexedExt.blendEquationSeparateiOES( index, gl.FUNC_ADD, gl.FUNC_ADD );
  48203. if ( premultipliedAlpha ) {
  48204. switch ( blendingType ) {
  48205. case NormalBlending:
  48206. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48207. break;
  48208. case AdditiveBlending:
  48209. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  48210. break;
  48211. case SubtractiveBlending:
  48212. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  48213. break;
  48214. case MultiplyBlending:
  48215. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  48216. break;
  48217. default:
  48218. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48219. break;
  48220. }
  48221. } else {
  48222. switch ( blendingType ) {
  48223. case NormalBlending:
  48224. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48225. break;
  48226. case AdditiveBlending:
  48227. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  48228. break;
  48229. case SubtractiveBlending:
  48230. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  48231. break;
  48232. case MultiplyBlending:
  48233. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  48234. break;
  48235. default:
  48236. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48237. break;
  48238. }
  48239. }
  48240. }
  48241. }
  48242. /**
  48243. * Defines the blending.
  48244. *
  48245. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  48246. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  48247. *
  48248. * @param {number} blending - The blending type.
  48249. * @param {number} blendEquation - The blending equation.
  48250. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  48251. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  48252. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  48253. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  48254. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  48255. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  48256. */
  48257. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  48258. const { gl } = this;
  48259. if ( blending === NoBlending ) {
  48260. if ( this.currentBlendingEnabled === true ) {
  48261. this.disable( gl.BLEND );
  48262. this.currentBlendingEnabled = false;
  48263. }
  48264. return;
  48265. }
  48266. if ( this.currentBlendingEnabled === false ) {
  48267. this.enable( gl.BLEND );
  48268. this.currentBlendingEnabled = true;
  48269. }
  48270. if ( blending !== CustomBlending ) {
  48271. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  48272. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  48273. gl.blendEquation( gl.FUNC_ADD );
  48274. this.currentBlendEquation = AddEquation;
  48275. this.currentBlendEquationAlpha = AddEquation;
  48276. }
  48277. if ( premultipliedAlpha ) {
  48278. switch ( blending ) {
  48279. case NormalBlending:
  48280. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48281. break;
  48282. case AdditiveBlending:
  48283. gl.blendFunc( gl.ONE, gl.ONE );
  48284. break;
  48285. case SubtractiveBlending:
  48286. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  48287. break;
  48288. case MultiplyBlending:
  48289. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  48290. break;
  48291. default:
  48292. error( 'WebGLState: Invalid blending: ', blending );
  48293. break;
  48294. }
  48295. } else {
  48296. switch ( blending ) {
  48297. case NormalBlending:
  48298. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48299. break;
  48300. case AdditiveBlending:
  48301. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  48302. break;
  48303. case SubtractiveBlending:
  48304. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  48305. break;
  48306. case MultiplyBlending:
  48307. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  48308. break;
  48309. default:
  48310. error( 'WebGLState: Invalid blending: ', blending );
  48311. break;
  48312. }
  48313. }
  48314. this.currentBlendSrc = null;
  48315. this.currentBlendDst = null;
  48316. this.currentBlendSrcAlpha = null;
  48317. this.currentBlendDstAlpha = null;
  48318. this.currentBlending = blending;
  48319. this.currentPremultipledAlpha = premultipliedAlpha;
  48320. }
  48321. return;
  48322. }
  48323. // custom blending
  48324. blendEquationAlpha = blendEquationAlpha || blendEquation;
  48325. blendSrcAlpha = blendSrcAlpha || blendSrc;
  48326. blendDstAlpha = blendDstAlpha || blendDst;
  48327. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  48328. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  48329. this.currentBlendEquation = blendEquation;
  48330. this.currentBlendEquationAlpha = blendEquationAlpha;
  48331. }
  48332. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  48333. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  48334. this.currentBlendSrc = blendSrc;
  48335. this.currentBlendDst = blendDst;
  48336. this.currentBlendSrcAlpha = blendSrcAlpha;
  48337. this.currentBlendDstAlpha = blendDstAlpha;
  48338. }
  48339. this.currentBlending = blending;
  48340. this.currentPremultipledAlpha = false;
  48341. }
  48342. /**
  48343. * Specifies whether colors can be written when rendering
  48344. * into a framebuffer or not.
  48345. *
  48346. * This method caches the state so `gl.colorMask()` is only
  48347. * called when necessary.
  48348. *
  48349. * @param {boolean} colorMask - The color mask.
  48350. */
  48351. setColorMask( colorMask ) {
  48352. if ( this.currentColorMask !== colorMask ) {
  48353. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  48354. this.currentColorMask = colorMask;
  48355. }
  48356. }
  48357. /**
  48358. * Specifies whether the depth test is enabled or not.
  48359. *
  48360. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  48361. */
  48362. setDepthTest( depthTest ) {
  48363. const { gl } = this;
  48364. if ( depthTest ) {
  48365. this.enable( gl.DEPTH_TEST );
  48366. } else {
  48367. this.disable( gl.DEPTH_TEST );
  48368. }
  48369. }
  48370. /**
  48371. * Configures the WebGL state to use a reversed depth buffer.
  48372. *
  48373. * @param {boolean} reversed - Whether the depth buffer is reversed or not.
  48374. */
  48375. setReversedDepth( reversed ) {
  48376. if ( this.currentDepthReversed !== reversed ) {
  48377. const ext = this.backend.extensions.get( 'EXT_clip_control' );
  48378. if ( reversed ) {
  48379. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  48380. } else {
  48381. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  48382. }
  48383. this.currentDepthReversed = reversed;
  48384. }
  48385. }
  48386. /**
  48387. * Specifies whether depth values can be written when rendering
  48388. * into a framebuffer or not.
  48389. *
  48390. * This method caches the state so `gl.depthMask()` is only
  48391. * called when necessary.
  48392. *
  48393. * @param {boolean} depthMask - The depth mask.
  48394. */
  48395. setDepthMask( depthMask ) {
  48396. if ( this.currentDepthMask !== depthMask ) {
  48397. this.gl.depthMask( depthMask );
  48398. this.currentDepthMask = depthMask;
  48399. }
  48400. }
  48401. /**
  48402. * Specifies the depth compare function.
  48403. *
  48404. * This method caches the state so `gl.depthFunc()` is only
  48405. * called when necessary.
  48406. *
  48407. * @param {number} depthFunc - The depth compare function.
  48408. */
  48409. setDepthFunc( depthFunc ) {
  48410. if ( this.currentDepthReversed ) depthFunc = ReversedDepthFuncs[ depthFunc ];
  48411. if ( this.currentDepthFunc !== depthFunc ) {
  48412. const { gl } = this;
  48413. switch ( depthFunc ) {
  48414. case NeverDepth:
  48415. gl.depthFunc( gl.NEVER );
  48416. break;
  48417. case AlwaysDepth:
  48418. gl.depthFunc( gl.ALWAYS );
  48419. break;
  48420. case LessDepth:
  48421. gl.depthFunc( gl.LESS );
  48422. break;
  48423. case LessEqualDepth:
  48424. gl.depthFunc( gl.LEQUAL );
  48425. break;
  48426. case EqualDepth:
  48427. gl.depthFunc( gl.EQUAL );
  48428. break;
  48429. case GreaterEqualDepth:
  48430. gl.depthFunc( gl.GEQUAL );
  48431. break;
  48432. case GreaterDepth:
  48433. gl.depthFunc( gl.GREATER );
  48434. break;
  48435. case NotEqualDepth:
  48436. gl.depthFunc( gl.NOTEQUAL );
  48437. break;
  48438. default:
  48439. gl.depthFunc( gl.LEQUAL );
  48440. }
  48441. this.currentDepthFunc = depthFunc;
  48442. }
  48443. }
  48444. /**
  48445. * Specifies the scissor box.
  48446. *
  48447. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  48448. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  48449. * @param {number} width - The width of the viewport.
  48450. * @param {number} height - The height of the viewport.
  48451. *
  48452. */
  48453. scissor( x, y, width, height ) {
  48454. const scissor = this._tempVec4.set( x, y, width, height );
  48455. if ( this.currentScissor.equals( scissor ) === false ) {
  48456. const { gl } = this;
  48457. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  48458. this.currentScissor.copy( scissor );
  48459. }
  48460. }
  48461. /**
  48462. * Specifies the viewport.
  48463. *
  48464. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  48465. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  48466. * @param {number} width - The width of the viewport.
  48467. * @param {number} height - The height of the viewport.
  48468. *
  48469. */
  48470. viewport( x, y, width, height ) {
  48471. const viewport = this._tempVec4.set( x, y, width, height );
  48472. if ( this.currentViewport.equals( viewport ) === false ) {
  48473. const { gl } = this;
  48474. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  48475. this.currentViewport.copy( viewport );
  48476. }
  48477. }
  48478. /**
  48479. * Defines the scissor test.
  48480. *
  48481. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  48482. */
  48483. setScissorTest( boolean ) {
  48484. const gl = this.gl;
  48485. if ( boolean ) {
  48486. this.enable( gl.SCISSOR_TEST );
  48487. } else {
  48488. this.disable( gl.SCISSOR_TEST );
  48489. }
  48490. }
  48491. /**
  48492. * Specifies whether the stencil test is enabled or not.
  48493. *
  48494. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  48495. */
  48496. setStencilTest( stencilTest ) {
  48497. const { gl } = this;
  48498. if ( stencilTest ) {
  48499. this.enable( gl.STENCIL_TEST );
  48500. } else {
  48501. this.disable( gl.STENCIL_TEST );
  48502. }
  48503. }
  48504. /**
  48505. * Specifies whether stencil values can be written when rendering
  48506. * into a framebuffer or not.
  48507. *
  48508. * This method caches the state so `gl.stencilMask()` is only
  48509. * called when necessary.
  48510. *
  48511. * @param {boolean} stencilMask - The stencil mask.
  48512. */
  48513. setStencilMask( stencilMask ) {
  48514. if ( this.currentStencilMask !== stencilMask ) {
  48515. this.gl.stencilMask( stencilMask );
  48516. this.currentStencilMask = stencilMask;
  48517. }
  48518. }
  48519. /**
  48520. * Specifies whether the stencil test functions.
  48521. *
  48522. * This method caches the state so `gl.stencilFunc()` is only
  48523. * called when necessary.
  48524. *
  48525. * @param {number} stencilFunc - The stencil compare function.
  48526. * @param {number} stencilRef - The reference value for the stencil test.
  48527. * @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.
  48528. */
  48529. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  48530. if ( this.currentStencilFunc !== stencilFunc ||
  48531. this.currentStencilRef !== stencilRef ||
  48532. this.currentStencilFuncMask !== stencilMask ) {
  48533. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  48534. this.currentStencilFunc = stencilFunc;
  48535. this.currentStencilRef = stencilRef;
  48536. this.currentStencilFuncMask = stencilMask;
  48537. }
  48538. }
  48539. /**
  48540. * Specifies whether the stencil test operation.
  48541. *
  48542. * This method caches the state so `gl.stencilOp()` is only
  48543. * called when necessary.
  48544. *
  48545. * @param {number} stencilFail - The function to use when the stencil test fails.
  48546. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  48547. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  48548. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  48549. */
  48550. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  48551. if ( this.currentStencilFail !== stencilFail ||
  48552. this.currentStencilZFail !== stencilZFail ||
  48553. this.currentStencilZPass !== stencilZPass ) {
  48554. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  48555. this.currentStencilFail = stencilFail;
  48556. this.currentStencilZFail = stencilZFail;
  48557. this.currentStencilZPass = stencilZPass;
  48558. }
  48559. }
  48560. /**
  48561. * Configures the WebGL state for the given material.
  48562. *
  48563. * @param {Material} material - The material to configure the state for.
  48564. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  48565. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  48566. */
  48567. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  48568. const { gl } = this;
  48569. material.side === DoubleSide
  48570. ? this.disable( gl.CULL_FACE )
  48571. : this.enable( gl.CULL_FACE );
  48572. let flipSided = ( material.side === BackSide );
  48573. if ( frontFaceCW ) flipSided = ! flipSided;
  48574. this.setFlipSided( flipSided );
  48575. ( material.blending === NormalBlending && material.transparent === false )
  48576. ? this.setBlending( NoBlending )
  48577. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  48578. this.setDepthFunc( material.depthFunc );
  48579. this.setDepthTest( material.depthTest );
  48580. this.setDepthMask( material.depthWrite );
  48581. this.setColorMask( material.colorWrite );
  48582. const stencilWrite = material.stencilWrite;
  48583. this.setStencilTest( stencilWrite );
  48584. if ( stencilWrite ) {
  48585. this.setStencilMask( material.stencilWriteMask );
  48586. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  48587. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  48588. }
  48589. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  48590. material.alphaToCoverage === true && this.backend.renderer.currentSamples > 0
  48591. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  48592. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  48593. if ( hardwareClippingPlanes > 0 ) {
  48594. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  48595. const CLIP_DISTANCE0_WEBGL = 0x3000;
  48596. for ( let i = 0; i < 8; i ++ ) {
  48597. if ( i < hardwareClippingPlanes ) {
  48598. this.enable( CLIP_DISTANCE0_WEBGL + i );
  48599. } else {
  48600. this.disable( CLIP_DISTANCE0_WEBGL + i );
  48601. }
  48602. }
  48603. }
  48604. }
  48605. }
  48606. /**
  48607. * Specifies the polygon offset.
  48608. *
  48609. * This method caches the state so `gl.polygonOffset()` is only
  48610. * called when necessary.
  48611. *
  48612. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  48613. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  48614. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  48615. */
  48616. setPolygonOffset( polygonOffset, factor, units ) {
  48617. const { gl } = this;
  48618. if ( polygonOffset ) {
  48619. this.enable( gl.POLYGON_OFFSET_FILL );
  48620. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  48621. gl.polygonOffset( factor, units );
  48622. this.currentPolygonOffsetFactor = factor;
  48623. this.currentPolygonOffsetUnits = units;
  48624. }
  48625. } else {
  48626. this.disable( gl.POLYGON_OFFSET_FILL );
  48627. }
  48628. }
  48629. /**
  48630. * Defines the usage of the given WebGL program.
  48631. *
  48632. * This method caches the state so `gl.useProgram()` is only
  48633. * called when necessary.
  48634. *
  48635. * @param {WebGLProgram} program - The WebGL program to use.
  48636. * @return {boolean} Whether a program change has been executed or not.
  48637. */
  48638. useProgram( program ) {
  48639. if ( this.currentProgram !== program ) {
  48640. this.gl.useProgram( program );
  48641. this.currentProgram = program;
  48642. return true;
  48643. }
  48644. return false;
  48645. }
  48646. /**
  48647. * Sets the vertex state by binding the given VAO and element buffer.
  48648. *
  48649. * @param {WebGLVertexArrayObject} vao - The VAO.
  48650. * @param {?WebGLBuffer} indexBuffer - The index buffer.
  48651. * @return {boolean} Whether a vertex state has been changed or not.
  48652. */
  48653. setVertexState( vao, indexBuffer = null ) {
  48654. const gl = this.gl;
  48655. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  48656. gl.bindVertexArray( vao );
  48657. if ( indexBuffer !== null ) {
  48658. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  48659. }
  48660. this.currentVAO = vao;
  48661. this.currentIndex = indexBuffer;
  48662. return true;
  48663. }
  48664. return false;
  48665. }
  48666. /**
  48667. * Resets the vertex array state by resetting the VAO and element buffer.
  48668. */
  48669. resetVertexState() {
  48670. const gl = this.gl;
  48671. gl.bindVertexArray( null );
  48672. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  48673. this.currentVAO = null;
  48674. this.currentIndex = null;
  48675. }
  48676. // framebuffer
  48677. /**
  48678. * Binds the given framebuffer.
  48679. *
  48680. * This method caches the state so `gl.bindFramebuffer()` is only
  48681. * called when necessary.
  48682. *
  48683. * @param {number} target - The binding point (target).
  48684. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  48685. * @return {boolean} Whether a bind has been executed or not.
  48686. */
  48687. bindFramebuffer( target, framebuffer ) {
  48688. const { gl, currentBoundFramebuffers } = this;
  48689. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  48690. gl.bindFramebuffer( target, framebuffer );
  48691. currentBoundFramebuffers[ target ] = framebuffer;
  48692. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  48693. if ( target === gl.DRAW_FRAMEBUFFER ) {
  48694. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  48695. }
  48696. if ( target === gl.FRAMEBUFFER ) {
  48697. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  48698. }
  48699. return true;
  48700. }
  48701. return false;
  48702. }
  48703. /**
  48704. * Defines draw buffers to which fragment colors are written into.
  48705. * Configures the MRT setup of custom framebuffers.
  48706. *
  48707. * This method caches the state so `gl.drawBuffers()` is only
  48708. * called when necessary.
  48709. *
  48710. * @param {RenderContext} renderContext - The render context.
  48711. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  48712. */
  48713. drawBuffers( renderContext, framebuffer ) {
  48714. const { gl } = this;
  48715. let drawBuffers = [];
  48716. let needsUpdate = false;
  48717. if ( renderContext.textures !== null ) {
  48718. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  48719. if ( drawBuffers === undefined ) {
  48720. drawBuffers = [];
  48721. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  48722. }
  48723. const textures = renderContext.textures;
  48724. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  48725. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  48726. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  48727. }
  48728. drawBuffers.length = textures.length;
  48729. needsUpdate = true;
  48730. }
  48731. } else {
  48732. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  48733. drawBuffers[ 0 ] = gl.BACK;
  48734. needsUpdate = true;
  48735. }
  48736. }
  48737. if ( needsUpdate ) {
  48738. gl.drawBuffers( drawBuffers );
  48739. }
  48740. }
  48741. // texture
  48742. /**
  48743. * Makes the given texture unit active.
  48744. *
  48745. * This method caches the state so `gl.activeTexture()` is only
  48746. * called when necessary.
  48747. *
  48748. * @param {number} webglSlot - The texture unit to make active.
  48749. */
  48750. activeTexture( webglSlot ) {
  48751. const { gl, currentTextureSlot, maxTextures } = this;
  48752. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  48753. if ( currentTextureSlot !== webglSlot ) {
  48754. gl.activeTexture( webglSlot );
  48755. this.currentTextureSlot = webglSlot;
  48756. }
  48757. }
  48758. /**
  48759. * Binds the given WebGL texture to a target.
  48760. *
  48761. * This method caches the state so `gl.bindTexture()` is only
  48762. * called when necessary.
  48763. *
  48764. * @param {number} webglType - The binding point (target).
  48765. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  48766. * @param {number} webglSlot - The texture.
  48767. */
  48768. bindTexture( webglType, webglTexture, webglSlot ) {
  48769. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  48770. if ( webglSlot === undefined ) {
  48771. if ( currentTextureSlot === null ) {
  48772. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  48773. } else {
  48774. webglSlot = currentTextureSlot;
  48775. }
  48776. }
  48777. let boundTexture = currentBoundTextures[ webglSlot ];
  48778. if ( boundTexture === undefined ) {
  48779. boundTexture = { type: undefined, texture: undefined };
  48780. currentBoundTextures[ webglSlot ] = boundTexture;
  48781. }
  48782. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  48783. if ( currentTextureSlot !== webglSlot ) {
  48784. gl.activeTexture( webglSlot );
  48785. this.currentTextureSlot = webglSlot;
  48786. }
  48787. gl.bindTexture( webglType, webglTexture );
  48788. boundTexture.type = webglType;
  48789. boundTexture.texture = webglTexture;
  48790. }
  48791. }
  48792. /**
  48793. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  48794. *
  48795. * This method caches the state so `gl.bindBufferBase()` is only
  48796. * called when necessary.
  48797. *
  48798. * @param {number} target - The target for the bind operation.
  48799. * @param {number} index - The index of the target.
  48800. * @param {WebGLBuffer} buffer - The WebGL buffer.
  48801. * @return {boolean} Whether a bind has been executed or not.
  48802. */
  48803. bindBufferBase( target, index, buffer ) {
  48804. const { gl } = this;
  48805. const key = `${target}-${index}`;
  48806. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  48807. gl.bindBufferBase( target, index, buffer );
  48808. this.currentBoundBufferBases[ key ] = buffer;
  48809. return true;
  48810. }
  48811. return false;
  48812. }
  48813. /**
  48814. * Unbinds the current bound texture.
  48815. *
  48816. * This method caches the state so `gl.bindTexture()` is only
  48817. * called when necessary.
  48818. */
  48819. unbindTexture() {
  48820. const { gl, currentTextureSlot, currentBoundTextures } = this;
  48821. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  48822. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  48823. gl.bindTexture( boundTexture.type, null );
  48824. boundTexture.type = undefined;
  48825. boundTexture.texture = undefined;
  48826. }
  48827. }
  48828. /**
  48829. * Returns the value for the given parameter.
  48830. *
  48831. * @param {number} name - The paramter to get the value for.
  48832. * @return {any} The value for the given parameter.
  48833. */
  48834. getParameter( name ) {
  48835. const { gl, parameters } = this;
  48836. if ( parameters[ name ] !== undefined ) {
  48837. return parameters[ name ];
  48838. } else {
  48839. return gl.getParameter( name );
  48840. }
  48841. }
  48842. /**
  48843. * Specifies a pixel storage mode.
  48844. *
  48845. * @param {number} name - The parameter to set.
  48846. * @param {any} value - A value to set the parameter to.
  48847. */
  48848. pixelStorei( name, value ) {
  48849. const { gl, parameters } = this;
  48850. if ( parameters[ name ] !== value ) {
  48851. gl.pixelStorei( name, value );
  48852. parameters[ name ] = value;
  48853. }
  48854. }
  48855. }
  48856. /**
  48857. * A WebGL 2 backend utility module with common helpers.
  48858. *
  48859. * @private
  48860. */
  48861. class WebGLUtils {
  48862. /**
  48863. * Constructs a new utility object.
  48864. *
  48865. * @param {WebGLBackend} backend - The WebGL 2 backend.
  48866. */
  48867. constructor( backend ) {
  48868. /**
  48869. * A reference to the WebGL 2 backend.
  48870. *
  48871. * @type {WebGLBackend}
  48872. */
  48873. this.backend = backend;
  48874. /**
  48875. * A reference to the rendering context.
  48876. *
  48877. * @type {WebGL2RenderingContext}
  48878. */
  48879. this.gl = this.backend.gl;
  48880. /**
  48881. * A reference to a backend module holding extension-related
  48882. * utility functions.
  48883. *
  48884. * @type {WebGLExtensions}
  48885. */
  48886. this.extensions = backend.extensions;
  48887. }
  48888. /**
  48889. * Converts the given three.js constant into a WebGL constant.
  48890. * The method currently supports the conversion of texture formats
  48891. * and types.
  48892. *
  48893. * @param {number} p - The three.js constant.
  48894. * @param {string} [colorSpace=NoColorSpace] - The color space.
  48895. * @return {?number} The corresponding WebGL constant.
  48896. */
  48897. convert( p, colorSpace = NoColorSpace ) {
  48898. const { gl, extensions } = this;
  48899. let extension;
  48900. const transfer = ColorManagement.getTransfer( colorSpace );
  48901. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  48902. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  48903. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  48904. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  48905. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  48906. if ( p === ByteType ) return gl.BYTE;
  48907. if ( p === ShortType ) return gl.SHORT;
  48908. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  48909. if ( p === IntType ) return gl.INT;
  48910. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  48911. if ( p === FloatType ) return gl.FLOAT;
  48912. if ( p === HalfFloatType ) {
  48913. return gl.HALF_FLOAT;
  48914. }
  48915. if ( p === AlphaFormat ) return gl.ALPHA;
  48916. if ( p === RGBFormat ) return gl.RGB;
  48917. if ( p === RGBAFormat ) return gl.RGBA;
  48918. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  48919. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  48920. // WebGL2 formats.
  48921. if ( p === RedFormat ) return gl.RED;
  48922. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  48923. if ( p === RGFormat ) return gl.RG;
  48924. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  48925. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  48926. // S3TC
  48927. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  48928. if ( transfer === SRGBTransfer ) {
  48929. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  48930. if ( extension !== null ) {
  48931. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  48932. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  48933. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  48934. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  48935. } else {
  48936. return null;
  48937. }
  48938. } else {
  48939. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  48940. if ( extension !== null ) {
  48941. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  48942. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  48943. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  48944. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  48945. } else {
  48946. return null;
  48947. }
  48948. }
  48949. }
  48950. // PVRTC
  48951. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  48952. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  48953. if ( extension !== null ) {
  48954. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  48955. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  48956. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  48957. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  48958. } else {
  48959. return null;
  48960. }
  48961. }
  48962. // ETC
  48963. 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 ) {
  48964. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  48965. if ( extension !== null ) {
  48966. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  48967. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  48968. if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC;
  48969. if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC;
  48970. if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC;
  48971. if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC;
  48972. } else {
  48973. return null;
  48974. }
  48975. }
  48976. // ASTC
  48977. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  48978. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  48979. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  48980. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  48981. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  48982. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  48983. if ( extension !== null ) {
  48984. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  48985. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  48986. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  48987. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  48988. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  48989. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  48990. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  48991. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  48992. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  48993. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  48994. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  48995. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  48996. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  48997. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  48998. } else {
  48999. return null;
  49000. }
  49001. }
  49002. // BPTC
  49003. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  49004. extension = extensions.get( 'EXT_texture_compression_bptc' );
  49005. if ( extension !== null ) {
  49006. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  49007. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  49008. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  49009. } else {
  49010. return null;
  49011. }
  49012. }
  49013. // RGTC
  49014. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  49015. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  49016. if ( extension !== null ) {
  49017. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  49018. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  49019. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  49020. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  49021. } else {
  49022. return null;
  49023. }
  49024. }
  49025. //
  49026. if ( p === UnsignedInt248Type ) {
  49027. return gl.UNSIGNED_INT_24_8;
  49028. }
  49029. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  49030. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  49031. }
  49032. /**
  49033. * This method can be used to synchronize the CPU with the GPU by waiting until
  49034. * ongoing GPU commands have been completed.
  49035. *
  49036. * @private
  49037. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  49038. */
  49039. _clientWaitAsync() {
  49040. const { gl } = this;
  49041. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  49042. gl.flush();
  49043. return new Promise( ( resolve, reject ) => {
  49044. function test() {
  49045. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  49046. if ( res === gl.WAIT_FAILED ) {
  49047. gl.deleteSync( sync );
  49048. reject();
  49049. return;
  49050. }
  49051. if ( res === gl.TIMEOUT_EXPIRED ) {
  49052. requestAnimationFrame( test );
  49053. return;
  49054. }
  49055. gl.deleteSync( sync );
  49056. resolve();
  49057. }
  49058. test();
  49059. } );
  49060. }
  49061. }
  49062. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  49063. /**
  49064. * A WebGL 2 backend utility module for managing textures.
  49065. *
  49066. * @private
  49067. */
  49068. class WebGLTextureUtils {
  49069. /**
  49070. * Constructs a new utility object.
  49071. *
  49072. * @param {WebGLBackend} backend - The WebGL 2 backend.
  49073. */
  49074. constructor( backend ) {
  49075. /**
  49076. * A reference to the WebGL 2 backend.
  49077. *
  49078. * @type {WebGLBackend}
  49079. */
  49080. this.backend = backend;
  49081. /**
  49082. * A reference to the rendering context.
  49083. *
  49084. * @type {WebGL2RenderingContext}
  49085. */
  49086. this.gl = backend.gl;
  49087. /**
  49088. * A reference to a backend module holding extension-related
  49089. * utility functions.
  49090. *
  49091. * @type {WebGLExtensions}
  49092. */
  49093. this.extensions = backend.extensions;
  49094. /**
  49095. * A dictionary for managing default textures. The key
  49096. * is the binding point (target), the value the WEbGL texture object.
  49097. *
  49098. * @type {Object<GLenum,WebGLTexture>}
  49099. */
  49100. this.defaultTextures = {};
  49101. /**
  49102. * A scratch framebuffer used for attaching the source texture in
  49103. * {@link copyTextureToTexture}.
  49104. *
  49105. * @private
  49106. * @type {?WebGLFramebuffer}
  49107. */
  49108. this._srcFramebuffer = null;
  49109. /**
  49110. * A scratch framebuffer used for attaching the destination texture in
  49111. * {@link copyTextureToTexture}.
  49112. *
  49113. * @private
  49114. * @type {?WebGLFramebuffer}
  49115. */
  49116. this._dstFramebuffer = null;
  49117. if ( initialized === false ) {
  49118. this._init();
  49119. initialized = true;
  49120. }
  49121. }
  49122. /**
  49123. * Inits the state of the utility.
  49124. *
  49125. * @private
  49126. */
  49127. _init() {
  49128. const gl = this.gl;
  49129. // Store only WebGL constants here.
  49130. wrappingToGL = {
  49131. [ RepeatWrapping ]: gl.REPEAT,
  49132. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  49133. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  49134. };
  49135. filterToGL = {
  49136. [ NearestFilter ]: gl.NEAREST,
  49137. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  49138. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  49139. [ LinearFilter ]: gl.LINEAR,
  49140. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  49141. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  49142. };
  49143. compareToGL = {
  49144. [ NeverCompare ]: gl.NEVER,
  49145. [ AlwaysCompare ]: gl.ALWAYS,
  49146. [ LessCompare ]: gl.LESS,
  49147. [ LessEqualCompare ]: gl.LEQUAL,
  49148. [ EqualCompare ]: gl.EQUAL,
  49149. [ GreaterEqualCompare ]: gl.GEQUAL,
  49150. [ GreaterCompare ]: gl.GREATER,
  49151. [ NotEqualCompare ]: gl.NOTEQUAL
  49152. };
  49153. }
  49154. /**
  49155. * Returns the native texture type for the given texture.
  49156. *
  49157. * @param {Texture} texture - The texture.
  49158. * @return {GLenum} The native texture type.
  49159. */
  49160. getGLTextureType( texture ) {
  49161. const { gl } = this;
  49162. let glTextureType;
  49163. if ( texture.isCubeTexture === true ) {
  49164. glTextureType = gl.TEXTURE_CUBE_MAP;
  49165. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  49166. glTextureType = gl.TEXTURE_2D_ARRAY;
  49167. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  49168. glTextureType = gl.TEXTURE_3D;
  49169. } else {
  49170. glTextureType = gl.TEXTURE_2D;
  49171. }
  49172. return glTextureType;
  49173. }
  49174. /**
  49175. * Returns the native texture type for the given texture.
  49176. *
  49177. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  49178. * @param {GLenum} glFormat - The WebGL format.
  49179. * @param {GLenum} glType - The WebGL type.
  49180. * @param {string} colorSpace - The texture's color space.
  49181. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  49182. * @return {GLenum} The internal format.
  49183. */
  49184. getInternalFormat( internalFormatName, glFormat, glType, normalized, colorSpace, forceLinearTransfer = false ) {
  49185. const { gl, extensions } = this;
  49186. if ( internalFormatName !== null ) {
  49187. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  49188. warn( 'WebGLBackend: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  49189. }
  49190. let extTextureNorm16 = null;
  49191. if ( normalized ) {
  49192. extTextureNorm16 = extensions.get( 'EXT_texture_norm16' );
  49193. if ( ! extTextureNorm16 ) {
  49194. warn( 'WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension' );
  49195. }
  49196. }
  49197. let internalFormat = glFormat;
  49198. if ( glFormat === gl.RED ) {
  49199. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  49200. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  49201. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  49202. if ( glType === gl.BYTE ) internalFormat = gl.R8_SNORM;
  49203. if ( glType === gl.UNSIGNED_SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.R16_EXT;
  49204. if ( glType === gl.SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.R16_SNORM_EXT;
  49205. }
  49206. if ( glFormat === gl.RED_INTEGER ) {
  49207. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  49208. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  49209. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  49210. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  49211. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  49212. if ( glType === gl.INT ) internalFormat = gl.R32I;
  49213. }
  49214. if ( glFormat === gl.RG ) {
  49215. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  49216. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  49217. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  49218. if ( glType === gl.BYTE ) internalFormat = gl.RG8_SNORM;
  49219. if ( glType === gl.UNSIGNED_SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.RG16_EXT;
  49220. if ( glType === gl.SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.RG16_SNORM_EXT;
  49221. }
  49222. if ( glFormat === gl.RG_INTEGER ) {
  49223. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  49224. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  49225. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  49226. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  49227. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  49228. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  49229. }
  49230. if ( glFormat === gl.RGB ) {
  49231. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  49232. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  49233. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  49234. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  49235. if ( glType === gl.BYTE ) internalFormat = gl.RGB8_SNORM;
  49236. if ( glType === gl.UNSIGNED_SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.RGB16_EXT;
  49237. if ( glType === gl.SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.RGB16_SNORM_EXT;
  49238. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  49239. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  49240. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  49241. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  49242. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  49243. }
  49244. if ( glFormat === gl.RGB_INTEGER ) {
  49245. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  49246. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  49247. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  49248. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  49249. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  49250. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  49251. }
  49252. if ( glFormat === gl.RGBA ) {
  49253. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  49254. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  49255. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  49256. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  49257. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8_SNORM;
  49258. if ( glType === gl.UNSIGNED_SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.RGBA16_EXT;
  49259. if ( glType === gl.SHORT && extTextureNorm16 ) internalFormat = extTextureNorm16.RGBA16_SNORM_EXT;
  49260. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  49261. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  49262. }
  49263. if ( glFormat === gl.RGBA_INTEGER ) {
  49264. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  49265. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  49266. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  49267. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  49268. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  49269. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  49270. }
  49271. if ( glFormat === gl.DEPTH_COMPONENT ) {
  49272. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  49273. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  49274. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  49275. }
  49276. if ( glFormat === gl.DEPTH_STENCIL ) {
  49277. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  49278. }
  49279. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  49280. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  49281. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  49282. extensions.get( 'EXT_color_buffer_float' );
  49283. }
  49284. return internalFormat;
  49285. }
  49286. /**
  49287. * Sets the texture parameters for the given texture.
  49288. *
  49289. * @param {GLenum} textureType - The texture type.
  49290. * @param {Texture} texture - The texture.
  49291. */
  49292. setTextureParameters( textureType, texture ) {
  49293. const { gl, extensions, backend } = this;
  49294. const { state } = this.backend;
  49295. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  49296. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  49297. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  49298. state.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  49299. state.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  49300. state.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  49301. state.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  49302. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  49303. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  49304. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  49305. // WebGL 2 does not support wrapping for depth 2D array textures
  49306. if ( ! texture.isArrayTexture ) {
  49307. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  49308. }
  49309. }
  49310. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  49311. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  49312. // follow WebGPU backend mapping for texture filtering
  49313. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  49314. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  49315. if ( texture.compareFunction ) {
  49316. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  49317. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  49318. }
  49319. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  49320. if ( texture.magFilter === NearestFilter ) return;
  49321. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  49322. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  49323. if ( texture.anisotropy > 1 ) {
  49324. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  49325. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.capabilities.getMaxAnisotropy() ) );
  49326. }
  49327. }
  49328. }
  49329. /**
  49330. * Creates a default texture for the given texture that can be used
  49331. * as a placeholder until the actual texture is ready for usage.
  49332. *
  49333. * @param {Texture} texture - The texture to create a default texture for.
  49334. */
  49335. createDefaultTexture( texture ) {
  49336. const { gl, backend, defaultTextures } = this;
  49337. const glTextureType = this.getGLTextureType( texture );
  49338. let textureGPU = defaultTextures[ glTextureType ];
  49339. if ( textureGPU === undefined ) {
  49340. textureGPU = gl.createTexture();
  49341. backend.state.bindTexture( glTextureType, textureGPU );
  49342. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  49343. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  49344. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  49345. defaultTextures[ glTextureType ] = textureGPU;
  49346. }
  49347. backend.set( texture, {
  49348. textureGPU,
  49349. glTextureType
  49350. } );
  49351. }
  49352. /**
  49353. * Defines a texture on the GPU for the given texture object.
  49354. *
  49355. * @param {Texture} texture - The texture.
  49356. * @param {Object} [options={}] - Optional configuration parameter.
  49357. * @return {undefined}
  49358. */
  49359. createTexture( texture, options ) {
  49360. const { gl, backend } = this;
  49361. const { levels, width, height, depth } = options;
  49362. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  49363. const glType = backend.utils.convert( texture.type );
  49364. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.normalized, texture.colorSpace, texture.isVideoTexture );
  49365. const textureGPU = gl.createTexture();
  49366. const glTextureType = this.getGLTextureType( texture );
  49367. backend.state.bindTexture( glTextureType, textureGPU );
  49368. this.setTextureParameters( glTextureType, texture );
  49369. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  49370. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  49371. } else if ( texture.isData3DTexture ) {
  49372. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  49373. } else if ( ! texture.isVideoTexture ) {
  49374. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  49375. }
  49376. backend.set( texture, {
  49377. textureGPU,
  49378. glTextureType,
  49379. glFormat,
  49380. glType,
  49381. glInternalFormat
  49382. } );
  49383. }
  49384. /**
  49385. * Uploads texture buffer data to the GPU memory.
  49386. *
  49387. * @param {WebGLBuffer} buffer - The buffer data.
  49388. * @param {Texture} texture - The texture,
  49389. */
  49390. copyBufferToTexture( buffer, texture ) {
  49391. const { gl, backend } = this;
  49392. const { state } = backend;
  49393. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  49394. const { width, height } = texture.source.data;
  49395. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  49396. backend.state.bindTexture( glTextureType, textureGPU );
  49397. state.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  49398. state.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  49399. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  49400. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  49401. backend.state.unbindTexture();
  49402. // debug
  49403. // const framebuffer = gl.createFramebuffer();
  49404. // backend.state.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  49405. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  49406. // const readout = new Float32Array( width * height * 4 );
  49407. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  49408. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  49409. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  49410. // backend.state.bindFramebuffer( gl.FRAMEBUFFER, null );
  49411. // log( readout );
  49412. }
  49413. /**
  49414. * Uploads the updated texture data to the GPU.
  49415. *
  49416. * @param {Texture} texture - The texture.
  49417. * @param {Object} [options={}] - Optional configuration parameter.
  49418. */
  49419. updateTexture( texture, options ) {
  49420. const { gl } = this;
  49421. const { width, height } = options;
  49422. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  49423. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  49424. return;
  49425. this.backend.state.bindTexture( glTextureType, textureGPU );
  49426. this.setTextureParameters( glTextureType, texture );
  49427. if ( texture.isCompressedTexture ) {
  49428. const mipmaps = texture.mipmaps;
  49429. const image = options.image;
  49430. for ( let i = 0; i < mipmaps.length; i ++ ) {
  49431. const mipmap = mipmaps[ i ];
  49432. if ( texture.isCompressedArrayTexture ) {
  49433. if ( texture.format !== gl.RGBA ) {
  49434. if ( glFormat !== null ) {
  49435. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  49436. } else {
  49437. warn( 'WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  49438. }
  49439. } else {
  49440. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  49441. }
  49442. } else {
  49443. if ( glFormat !== null ) {
  49444. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  49445. } else {
  49446. warn( 'WebGLBackend: Unsupported compressed texture format' );
  49447. }
  49448. }
  49449. }
  49450. } else if ( texture.isCubeTexture ) {
  49451. const images = options.images;
  49452. const mipmaps = texture.mipmaps;
  49453. for ( let i = 0; i < 6; i ++ ) {
  49454. const image = getImage( images[ i ] );
  49455. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  49456. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49457. const mipmap = mipmaps[ j ];
  49458. const image = getImage( mipmap.images[ i ] );
  49459. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  49460. }
  49461. }
  49462. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  49463. const image = options.image;
  49464. if ( texture.layerUpdates.size > 0 ) {
  49465. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  49466. for ( const layerIndex of texture.layerUpdates ) {
  49467. const layerData = image.data.subarray(
  49468. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  49469. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  49470. );
  49471. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  49472. }
  49473. texture.clearLayerUpdates();
  49474. } else {
  49475. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  49476. }
  49477. } else if ( texture.isData3DTexture ) {
  49478. const image = options.image;
  49479. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  49480. } else if ( texture.isVideoTexture ) {
  49481. texture.update();
  49482. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  49483. } else if ( texture.isHTMLTexture ) {
  49484. if ( typeof gl.texElementImage2D === 'function' ) {
  49485. if ( gl.texElementImage2D.length === 3 ) {
  49486. // Chrome 150+
  49487. gl.texElementImage2D( gl.TEXTURE_2D, gl.RGBA8, options.image );
  49488. } else {
  49489. // Chrome 138 - 149
  49490. gl.texElementImage2D( gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, options.image );
  49491. }
  49492. }
  49493. } else {
  49494. const mipmaps = texture.mipmaps;
  49495. if ( mipmaps.length > 0 ) {
  49496. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49497. const mipmap = mipmaps[ i ];
  49498. const image = getImage( mipmap );
  49499. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  49500. }
  49501. } else {
  49502. const image = getImage( options.image );
  49503. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  49504. }
  49505. }
  49506. }
  49507. /**
  49508. * Generates mipmaps for the given texture.
  49509. *
  49510. * @param {Texture} texture - The texture.
  49511. */
  49512. generateMipmaps( texture ) {
  49513. const { gl, backend } = this;
  49514. const { textureGPU, glTextureType } = backend.get( texture );
  49515. backend.state.bindTexture( glTextureType, textureGPU );
  49516. gl.generateMipmap( glTextureType );
  49517. }
  49518. /**
  49519. * Deallocates the render buffers of the given render target.
  49520. *
  49521. * @param {RenderTarget} renderTarget - The render target.
  49522. */
  49523. deallocateRenderBuffers( renderTarget ) {
  49524. const { gl, backend } = this;
  49525. // remove framebuffer reference
  49526. if ( renderTarget ) {
  49527. const renderContextData = backend.get( renderTarget );
  49528. renderContextData.renderBufferStorageSetup = undefined;
  49529. if ( renderContextData.framebuffers ) {
  49530. for ( const cacheKey in renderContextData.framebuffers ) {
  49531. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  49532. }
  49533. delete renderContextData.framebuffers;
  49534. }
  49535. if ( renderContextData.depthRenderbuffer ) {
  49536. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  49537. delete renderContextData.depthRenderbuffer;
  49538. }
  49539. if ( renderContextData.stencilRenderbuffer ) {
  49540. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  49541. delete renderContextData.stencilRenderbuffer;
  49542. }
  49543. if ( renderContextData.msaaFrameBuffer ) {
  49544. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  49545. delete renderContextData.msaaFrameBuffer;
  49546. }
  49547. if ( renderContextData.msaaRenderbuffers ) {
  49548. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  49549. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  49550. }
  49551. delete renderContextData.msaaRenderbuffers;
  49552. }
  49553. }
  49554. }
  49555. /**
  49556. * Destroys the GPU data for the given texture object.
  49557. *
  49558. * @param {Texture} texture - The texture.
  49559. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  49560. */
  49561. destroyTexture( texture, isDefaultTexture = false ) {
  49562. const { gl, backend } = this;
  49563. const { textureGPU, renderTarget } = backend.get( texture );
  49564. this.deallocateRenderBuffers( renderTarget );
  49565. if ( isDefaultTexture === false ) {
  49566. gl.deleteTexture( textureGPU );
  49567. }
  49568. backend.delete( texture );
  49569. }
  49570. /**
  49571. * Copies data of the given source texture to the given destination texture.
  49572. *
  49573. * @param {Texture} srcTexture - The source texture.
  49574. * @param {Texture} dstTexture - The destination texture.
  49575. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  49576. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  49577. * @param {number} [srcLevel=0] - The source mip level to copy from.
  49578. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  49579. */
  49580. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  49581. const { gl, backend } = this;
  49582. const { state } = this.backend;
  49583. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  49584. state.bindTexture( glTextureType, dstTextureGPU );
  49585. // gather the necessary dimensions to copy
  49586. let width, height, depth, minX, minY, minZ;
  49587. let dstX, dstY, dstZ;
  49588. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  49589. if ( srcRegion !== null ) {
  49590. width = srcRegion.max.x - srcRegion.min.x;
  49591. height = srcRegion.max.y - srcRegion.min.y;
  49592. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  49593. minX = srcRegion.min.x;
  49594. minY = srcRegion.min.y;
  49595. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  49596. } else {
  49597. const levelScale = Math.pow( 2, - srcLevel );
  49598. width = Math.floor( image.width * levelScale );
  49599. height = Math.floor( image.height * levelScale );
  49600. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  49601. depth = image.depth;
  49602. } else if ( srcTexture.isData3DTexture ) {
  49603. depth = Math.floor( image.depth * levelScale );
  49604. } else {
  49605. depth = 1;
  49606. }
  49607. minX = 0;
  49608. minY = 0;
  49609. minZ = 0;
  49610. }
  49611. if ( dstPosition !== null ) {
  49612. dstX = dstPosition.x;
  49613. dstY = dstPosition.y;
  49614. dstZ = dstPosition.z;
  49615. } else {
  49616. dstX = 0;
  49617. dstY = 0;
  49618. dstZ = 0;
  49619. }
  49620. state.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  49621. state.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  49622. state.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  49623. // used for copying data from cpu
  49624. const currentUnpackRowLen = state.getParameter( gl.UNPACK_ROW_LENGTH );
  49625. const currentUnpackImageHeight = state.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  49626. const currentUnpackSkipPixels = state.getParameter( gl.UNPACK_SKIP_PIXELS );
  49627. const currentUnpackSkipRows = state.getParameter( gl.UNPACK_SKIP_ROWS );
  49628. const currentUnpackSkipImages = state.getParameter( gl.UNPACK_SKIP_IMAGES );
  49629. state.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  49630. state.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  49631. state.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  49632. state.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  49633. state.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  49634. // set up the src texture
  49635. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture || dstTexture.isArrayTexture;
  49636. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  49637. if ( srcTexture.isDepthTexture ) {
  49638. const srcTextureData = backend.get( srcTexture );
  49639. const dstTextureData = backend.get( dstTexture );
  49640. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  49641. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  49642. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  49643. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  49644. const prevReadFramebuffer = state.currentBoundFramebuffers[ gl.READ_FRAMEBUFFER ] ?? null;
  49645. const prevDrawFramebuffer = state.currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] ?? null;
  49646. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  49647. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  49648. for ( let i = 0; i < depth; i ++ ) {
  49649. // if the source or destination are a 3d target then a layer needs to be bound
  49650. if ( isSrc3D ) {
  49651. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  49652. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  49653. }
  49654. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST );
  49655. }
  49656. state.bindFramebuffer( gl.READ_FRAMEBUFFER, prevReadFramebuffer );
  49657. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, prevDrawFramebuffer );
  49658. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || backend.has( srcTexture ) ) {
  49659. // get the appropriate frame buffers
  49660. const srcTextureData = backend.get( srcTexture );
  49661. if ( this._srcFramebuffer === null ) this._srcFramebuffer = gl.createFramebuffer();
  49662. if ( this._dstFramebuffer === null ) this._dstFramebuffer = gl.createFramebuffer();
  49663. const prevReadFramebuffer = state.currentBoundFramebuffers[ gl.READ_FRAMEBUFFER ] ?? null;
  49664. const prevDrawFramebuffer = state.currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] ?? null;
  49665. // bind the frame buffer targets
  49666. state.bindFramebuffer( gl.READ_FRAMEBUFFER, this._srcFramebuffer );
  49667. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, this._dstFramebuffer );
  49668. for ( let i = 0; i < depth; i ++ ) {
  49669. // assign the correct layers and mip maps to the frame buffers
  49670. if ( isSrc3D ) {
  49671. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  49672. } else {
  49673. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, srcTextureData.textureGPU, srcLevel );
  49674. }
  49675. if ( isDst3D ) {
  49676. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  49677. } else {
  49678. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dstTextureGPU, dstLevel );
  49679. }
  49680. // copy the data using the fastest function that can achieve the copy
  49681. if ( srcLevel !== 0 ) {
  49682. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST );
  49683. } else if ( isDst3D ) {
  49684. gl.copyTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  49685. } else {
  49686. gl.copyTexSubImage2D( glTextureType, dstLevel, dstX, dstY, minX, minY, width, height );
  49687. }
  49688. }
  49689. // restore previous read, draw framebuffer bindings
  49690. state.bindFramebuffer( gl.READ_FRAMEBUFFER, prevReadFramebuffer );
  49691. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, prevDrawFramebuffer );
  49692. } else {
  49693. if ( isDst3D ) {
  49694. // copy data into the 3d texture
  49695. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  49696. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  49697. } else if ( dstTexture.isCompressedArrayTexture ) {
  49698. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  49699. } else {
  49700. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  49701. }
  49702. } else {
  49703. // copy data into the 2d texture
  49704. if ( srcTexture.isDataTexture ) {
  49705. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  49706. } else if ( srcTexture.isCompressedTexture ) {
  49707. gl.compressedTexSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  49708. } else {
  49709. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  49710. }
  49711. }
  49712. }
  49713. // reset values
  49714. state.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  49715. state.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  49716. state.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  49717. state.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  49718. state.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  49719. // Generate mipmaps only when copying level 0
  49720. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  49721. gl.generateMipmap( glTextureType );
  49722. }
  49723. state.unbindTexture();
  49724. }
  49725. /**
  49726. * Copies the current bound framebuffer to the given texture.
  49727. *
  49728. * @param {Texture} texture - The destination texture.
  49729. * @param {RenderContext} renderContext - The render context.
  49730. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  49731. */
  49732. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  49733. const { gl } = this;
  49734. const { state } = this.backend;
  49735. const { textureGPU } = this.backend.get( texture );
  49736. const { x, y, z: width, w: height } = rectangle;
  49737. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  49738. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  49739. if ( requireDrawFrameBuffer ) {
  49740. const partial = ( x !== 0 || y !== 0 );
  49741. let mask;
  49742. let attachment;
  49743. if ( texture.isDepthTexture === true ) {
  49744. mask = gl.DEPTH_BUFFER_BIT;
  49745. attachment = gl.DEPTH_ATTACHMENT;
  49746. if ( renderContext.stencil ) {
  49747. mask |= gl.STENCIL_BUFFER_BIT;
  49748. }
  49749. } else {
  49750. mask = gl.COLOR_BUFFER_BIT;
  49751. attachment = gl.COLOR_ATTACHMENT0;
  49752. }
  49753. if ( partial ) {
  49754. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  49755. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  49756. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  49757. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  49758. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  49759. const flippedY = srcHeight - y - height;
  49760. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  49761. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  49762. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  49763. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  49764. state.unbindTexture();
  49765. } else {
  49766. const fb = gl.createFramebuffer();
  49767. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  49768. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  49769. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  49770. gl.deleteFramebuffer( fb );
  49771. }
  49772. } else {
  49773. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  49774. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  49775. state.unbindTexture();
  49776. }
  49777. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  49778. this.backend._setFramebuffer( renderContext );
  49779. }
  49780. /**
  49781. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  49782. *
  49783. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  49784. * @param {RenderContext} renderContext - The render context.
  49785. * @param {number} samples - The MSAA sample count.
  49786. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  49787. */
  49788. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  49789. const { gl } = this;
  49790. const renderTarget = renderContext.renderTarget;
  49791. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  49792. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  49793. if ( depthBuffer && ! stencilBuffer ) {
  49794. let glInternalFormat = gl.DEPTH_COMPONENT24;
  49795. if ( useMultisampledRTT === true ) {
  49796. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  49797. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  49798. } else if ( samples > 0 ) {
  49799. if ( depthTexture && depthTexture.isDepthTexture ) {
  49800. if ( depthTexture.type === gl.FLOAT ) {
  49801. glInternalFormat = gl.DEPTH_COMPONENT32F;
  49802. }
  49803. }
  49804. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  49805. } else {
  49806. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  49807. }
  49808. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  49809. } else if ( depthBuffer && stencilBuffer ) {
  49810. if ( samples > 0 ) {
  49811. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  49812. } else {
  49813. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  49814. }
  49815. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  49816. }
  49817. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  49818. }
  49819. /**
  49820. * Returns texture data as a typed array.
  49821. *
  49822. * @async
  49823. * @param {Texture} texture - The texture to copy.
  49824. * @param {number} x - The x coordinate of the copy origin.
  49825. * @param {number} y - The y coordinate of the copy origin.
  49826. * @param {number} width - The width of the copy.
  49827. * @param {number} height - The height of the copy.
  49828. * @param {number} faceIndex - The face index.
  49829. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  49830. */
  49831. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  49832. const { backend, gl } = this;
  49833. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  49834. const fb = gl.createFramebuffer();
  49835. backend.state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  49836. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  49837. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  49838. const typedArrayType = this._getTypedArrayType( glType );
  49839. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  49840. const elementCount = width * height;
  49841. const byteLength = elementCount * bytesPerTexel;
  49842. const buffer = gl.createBuffer();
  49843. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  49844. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  49845. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  49846. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  49847. await backend.utils._clientWaitAsync();
  49848. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  49849. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  49850. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  49851. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  49852. backend.state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  49853. gl.deleteFramebuffer( fb );
  49854. return dstBuffer;
  49855. }
  49856. /**
  49857. * Returns the corresponding typed array type for the given WebGL data type.
  49858. *
  49859. * @private
  49860. * @param {GLenum} glType - The WebGL data type.
  49861. * @return {TypedArray.constructor} The typed array type.
  49862. */
  49863. _getTypedArrayType( glType ) {
  49864. const { gl } = this;
  49865. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  49866. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  49867. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  49868. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  49869. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  49870. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  49871. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  49872. if ( glType === gl.FLOAT ) return Float32Array;
  49873. throw new Error( `THREE.WebGLTextureUtils: Unsupported WebGL type: ${glType}` );
  49874. }
  49875. /**
  49876. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  49877. *
  49878. * @private
  49879. * @param {GLenum} glType - The WebGL data type.
  49880. * @param {GLenum} glFormat - The WebGL texture format.
  49881. * @return {number} The bytes-per-texel.
  49882. */
  49883. _getBytesPerTexel( glType, glFormat ) {
  49884. const { gl } = this;
  49885. let bytesPerComponent = 0;
  49886. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  49887. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  49888. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  49889. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  49890. glType === gl.UNSIGNED_SHORT ||
  49891. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  49892. if ( glType === gl.UNSIGNED_INT ||
  49893. glType === gl.FLOAT ) bytesPerComponent = 4;
  49894. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  49895. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  49896. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  49897. }
  49898. /**
  49899. * Frees the internal resources.
  49900. */
  49901. dispose() {
  49902. const { gl } = this;
  49903. if ( this._srcFramebuffer !== null ) gl.deleteFramebuffer( this._srcFramebuffer );
  49904. if ( this._dstFramebuffer !== null ) gl.deleteFramebuffer( this._dstFramebuffer );
  49905. }
  49906. }
  49907. function getImage( source ) {
  49908. if ( source.isDataTexture ) {
  49909. return source.image.data;
  49910. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  49911. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  49912. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  49913. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  49914. return source;
  49915. }
  49916. return source.data;
  49917. }
  49918. /**
  49919. * A WebGL 2 backend utility module for managing extensions.
  49920. *
  49921. * @private
  49922. */
  49923. class WebGLExtensions {
  49924. /**
  49925. * Constructs a new utility object.
  49926. *
  49927. * @param {WebGLBackend} backend - The WebGL 2 backend.
  49928. */
  49929. constructor( backend ) {
  49930. /**
  49931. * A reference to the WebGL 2 backend.
  49932. *
  49933. * @type {WebGLBackend}
  49934. */
  49935. this.backend = backend;
  49936. /**
  49937. * A reference to the rendering context.
  49938. *
  49939. * @type {WebGL2RenderingContext}
  49940. */
  49941. this.gl = this.backend.gl;
  49942. /**
  49943. * A list with all the supported WebGL extensions.
  49944. *
  49945. * @type {Array<string>}
  49946. */
  49947. this.availableExtensions = this.gl.getSupportedExtensions();
  49948. /**
  49949. * A dictionary with requested WebGL extensions.
  49950. * The key is the name of the extension, the value
  49951. * the requested extension object.
  49952. *
  49953. * @type {Object<string,Object>}
  49954. */
  49955. this.extensions = {};
  49956. }
  49957. /**
  49958. * Returns the extension object for the given extension name.
  49959. *
  49960. * @param {string} name - The extension name.
  49961. * @return {Object} The extension object.
  49962. */
  49963. get( name ) {
  49964. let extension = this.extensions[ name ];
  49965. if ( extension === undefined ) {
  49966. extension = this.gl.getExtension( name );
  49967. this.extensions[ name ] = extension;
  49968. }
  49969. return extension;
  49970. }
  49971. /**
  49972. * Returns `true` if the requested extension is available.
  49973. *
  49974. * @param {string} name - The extension name.
  49975. * @return {boolean} Whether the given extension is available or not.
  49976. */
  49977. has( name ) {
  49978. return this.availableExtensions.includes( name );
  49979. }
  49980. }
  49981. /**
  49982. * A WebGL 2 backend utility module for managing the device's capabilities.
  49983. *
  49984. * @private
  49985. */
  49986. class WebGLCapabilities {
  49987. /**
  49988. * Constructs a new utility object.
  49989. *
  49990. * @param {WebGLBackend} backend - The WebGL 2 backend.
  49991. */
  49992. constructor( backend ) {
  49993. /**
  49994. * A reference to the WebGL 2 backend.
  49995. *
  49996. * @type {WebGLBackend}
  49997. */
  49998. this.backend = backend;
  49999. /**
  50000. * This value holds the cached max anisotropy value.
  50001. *
  50002. * @type {?number}
  50003. * @default null
  50004. */
  50005. this.maxAnisotropy = null;
  50006. /**
  50007. * This value holds the cached max uniform block size value.
  50008. *
  50009. * @type {?number}
  50010. * @default null
  50011. */
  50012. this.maxUniformBlockSize = null;
  50013. }
  50014. /**
  50015. * Returns the maximum anisotropy texture filtering value. This value
  50016. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  50017. * WebGL extension.
  50018. *
  50019. * @return {number} The maximum anisotropy texture filtering value.
  50020. */
  50021. getMaxAnisotropy() {
  50022. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  50023. const gl = this.backend.gl;
  50024. const extensions = this.backend.extensions;
  50025. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  50026. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  50027. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  50028. } else {
  50029. this.maxAnisotropy = 0;
  50030. }
  50031. return this.maxAnisotropy;
  50032. }
  50033. /**
  50034. * Returns the maximum number of bytes available for uniform buffers.
  50035. *
  50036. * @return {number} The maximum number of bytes available for uniform buffers.
  50037. */
  50038. getUniformBufferLimit() {
  50039. if ( this.maxUniformBlockSize !== null ) return this.maxUniformBlockSize;
  50040. const gl = this.backend.gl;
  50041. this.maxUniformBlockSize = gl.getParameter( gl.MAX_UNIFORM_BLOCK_SIZE );
  50042. return this.maxUniformBlockSize;
  50043. }
  50044. }
  50045. const GLFeatureName = {
  50046. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  50047. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  50048. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  50049. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  50050. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  50051. 'WEBGL_compressed_texture_s3tc': 'texture-compression-s3tc',
  50052. 'EXT_texture_compression_bptc': 'texture-compression-bc',
  50053. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  50054. 'OVR_multiview2': 'OVR_multiview2'
  50055. };
  50056. class WebGLBufferRenderer {
  50057. constructor( backend ) {
  50058. this.gl = backend.gl;
  50059. this.extensions = backend.extensions;
  50060. this.info = backend.renderer.info;
  50061. this.mode = null;
  50062. this.index = 0;
  50063. this.type = null;
  50064. this.object = null;
  50065. }
  50066. render( start, count ) {
  50067. const { gl, mode, object, type, info, index } = this;
  50068. if ( index !== 0 ) {
  50069. gl.drawElements( mode, count, type, start );
  50070. } else {
  50071. gl.drawArrays( mode, start, count );
  50072. }
  50073. info.update( object, count, 1 );
  50074. }
  50075. renderInstances( start, count, primcount ) {
  50076. const { gl, mode, type, index, object, info } = this;
  50077. if ( primcount === 0 ) return;
  50078. if ( index !== 0 ) {
  50079. gl.drawElementsInstanced( mode, count, type, start, primcount );
  50080. } else {
  50081. gl.drawArraysInstanced( mode, start, count, primcount );
  50082. }
  50083. info.update( object, count, primcount );
  50084. }
  50085. renderMultiDraw( starts, counts, drawCount ) {
  50086. const { extensions, mode, object, info } = this;
  50087. if ( drawCount === 0 ) return;
  50088. const extension = extensions.get( 'WEBGL_multi_draw' );
  50089. if ( extension === null ) {
  50090. for ( let i = 0; i < drawCount; i ++ ) {
  50091. this.render( starts[ i ], counts[ i ] );
  50092. }
  50093. } else {
  50094. if ( this.index !== 0 ) {
  50095. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  50096. } else {
  50097. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  50098. }
  50099. let elementCount = 0;
  50100. for ( let i = 0; i < drawCount; i ++ ) {
  50101. elementCount += counts[ i ];
  50102. }
  50103. info.update( object, elementCount, 1 );
  50104. }
  50105. }
  50106. //
  50107. }
  50108. /**
  50109. * Abstract base class of a timestamp query pool.
  50110. *
  50111. * @abstract
  50112. */
  50113. class TimestampQueryPool {
  50114. /**
  50115. * Creates a new timestamp query pool.
  50116. *
  50117. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  50118. */
  50119. constructor( maxQueries = 256 ) {
  50120. /**
  50121. * Whether to track timestamps or not.
  50122. *
  50123. * @type {boolean}
  50124. * @default true
  50125. */
  50126. this.trackTimestamp = true;
  50127. /**
  50128. * Maximum number of queries this pool can hold.
  50129. *
  50130. * @type {number}
  50131. * @default 256
  50132. */
  50133. this.maxQueries = maxQueries;
  50134. /**
  50135. * How many queries allocated so far.
  50136. *
  50137. * @type {number}
  50138. * @default 0
  50139. */
  50140. this.currentQueryIndex = 0;
  50141. /**
  50142. * Tracks offsets for different contexts.
  50143. *
  50144. * @type {Map<string, number>}
  50145. */
  50146. this.queryOffsets = new Map();
  50147. /**
  50148. * Whether the pool has been disposed or not.
  50149. *
  50150. * @type {boolean}
  50151. * @default false
  50152. */
  50153. this.isDisposed = false;
  50154. /**
  50155. * The total frame duration until the next update.
  50156. *
  50157. * @type {number}
  50158. * @default 0
  50159. */
  50160. this.lastValue = 0;
  50161. /**
  50162. * Stores all timestamp frames.
  50163. *
  50164. * @type {Array<number>}
  50165. */
  50166. this.frames = [];
  50167. /**
  50168. * This property is used to avoid multiple concurrent resolve operations.
  50169. * The WebGL backend uses it as a boolean flag. In context of WebGPU, it holds
  50170. * the promise of the current resolve operation.
  50171. *
  50172. * @type {boolean|Promise<number>}
  50173. * @default false
  50174. */
  50175. this.pendingResolve = false;
  50176. /**
  50177. * Stores the latest timestamp for each render context.
  50178. *
  50179. * @type {Map<string, number>}
  50180. */
  50181. this.timestamps = new Map();
  50182. }
  50183. /**
  50184. * Returns all timestamp frames.
  50185. *
  50186. * @return {Array<number>} The timestamp frames.
  50187. */
  50188. getTimestampFrames() {
  50189. return this.frames;
  50190. }
  50191. /**
  50192. * Returns the timestamp for a given render context.
  50193. *
  50194. * @param {string} uid - A unique identifier for the render context.
  50195. * @return {?number} The timestamp, or undefined if not available.
  50196. */
  50197. getTimestamp( uid ) {
  50198. let timestamp = this.timestamps.get( uid );
  50199. if ( timestamp === undefined ) {
  50200. warn( `TimestampQueryPool: No timestamp available for uid ${ uid }.` );
  50201. timestamp = 0;
  50202. }
  50203. return timestamp;
  50204. }
  50205. /**
  50206. * Returns whether a timestamp is available for a given render context.
  50207. *
  50208. * @param {string} uid - A unique identifier for the render context.
  50209. * @return {boolean} True if a timestamp is available, false otherwise.
  50210. */
  50211. hasTimestampQuery( uid ) {
  50212. return this.timestamps.has( uid );
  50213. }
  50214. /**
  50215. * Allocate queries for a specific uid.
  50216. *
  50217. * @abstract
  50218. * @param {string} uid - A unique identifier for the render context.
  50219. * @param {number} frameId - The current frame identifier.
  50220. * @returns {?number}
  50221. */
  50222. allocateQueriesForContext( /* uid, frameId */ ) {}
  50223. /**
  50224. * Resolve all timestamps and return data (or process them).
  50225. *
  50226. * @abstract
  50227. * @async
  50228. * @returns {Promise<number>|number} The resolved timestamp value.
  50229. */
  50230. async resolveQueriesAsync() {}
  50231. /**
  50232. * Dispose of the query pool.
  50233. *
  50234. * @abstract
  50235. */
  50236. dispose() {}
  50237. }
  50238. /**
  50239. * Manages a pool of WebGL timestamp queries for performance measurement.
  50240. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  50241. *
  50242. * @augments TimestampQueryPool
  50243. */
  50244. class WebGLTimestampQueryPool extends TimestampQueryPool {
  50245. /**
  50246. * Creates a new WebGL timestamp query pool.
  50247. *
  50248. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  50249. * @param {string} type - The type identifier for this query pool.
  50250. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  50251. */
  50252. constructor( gl, type, maxQueries = 2048 ) {
  50253. super( maxQueries );
  50254. this.gl = gl;
  50255. this.type = type;
  50256. // Check for timer query extensions
  50257. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  50258. gl.getExtension( 'EXT_disjoint_timer_query' );
  50259. if ( ! this.ext ) {
  50260. warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  50261. this.trackTimestamp = false;
  50262. return;
  50263. }
  50264. // Create query objects
  50265. this.queries = [];
  50266. for ( let i = 0; i < this.maxQueries; i ++ ) {
  50267. this.queries.push( gl.createQuery() );
  50268. }
  50269. this.activeQuery = null;
  50270. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  50271. }
  50272. /**
  50273. * Allocates a pair of queries for a given render context.
  50274. *
  50275. * @param {string} uid - A unique identifier for the render context.
  50276. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  50277. */
  50278. allocateQueriesForContext( uid ) {
  50279. if ( ! this.trackTimestamp ) return null;
  50280. // Check if we have enough space for a new query pair
  50281. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  50282. 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() } ).` );
  50283. return null;
  50284. }
  50285. const baseOffset = this.currentQueryIndex;
  50286. this.currentQueryIndex += 2;
  50287. // Initialize query states
  50288. this.queryStates.set( baseOffset, 'inactive' );
  50289. this.queryOffsets.set( uid, baseOffset );
  50290. return baseOffset;
  50291. }
  50292. /**
  50293. * Begins a timestamp query for the specified render context.
  50294. *
  50295. * @param {string} uid - A unique identifier for the render context.
  50296. */
  50297. beginQuery( uid ) {
  50298. if ( ! this.trackTimestamp || this.isDisposed ) {
  50299. return;
  50300. }
  50301. const baseOffset = this.queryOffsets.get( uid );
  50302. if ( baseOffset == null ) {
  50303. return;
  50304. }
  50305. // Don't start a new query if there's an active one
  50306. if ( this.activeQuery !== null ) {
  50307. return;
  50308. }
  50309. const query = this.queries[ baseOffset ];
  50310. if ( ! query ) {
  50311. return;
  50312. }
  50313. try {
  50314. // Only begin if query is inactive
  50315. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  50316. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  50317. this.activeQuery = baseOffset;
  50318. this.queryStates.set( baseOffset, 'started' );
  50319. }
  50320. } catch ( e ) {
  50321. error( 'Error in beginQuery:', e );
  50322. this.activeQuery = null;
  50323. this.queryStates.set( baseOffset, 'inactive' );
  50324. }
  50325. }
  50326. /**
  50327. * Ends the active timestamp query for the specified render context.
  50328. *
  50329. * @param {string} uid - A unique identifier for the render context.
  50330. */
  50331. endQuery( uid ) {
  50332. if ( ! this.trackTimestamp || this.isDisposed ) {
  50333. return;
  50334. }
  50335. const baseOffset = this.queryOffsets.get( uid );
  50336. if ( baseOffset == null ) {
  50337. return;
  50338. }
  50339. // Only end if this is the active query
  50340. if ( this.activeQuery !== baseOffset ) {
  50341. return;
  50342. }
  50343. try {
  50344. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  50345. this.queryStates.set( baseOffset, 'ended' );
  50346. this.activeQuery = null;
  50347. } catch ( e ) {
  50348. error( 'Error in endQuery:', e );
  50349. // Reset state on error
  50350. this.queryStates.set( baseOffset, 'inactive' );
  50351. this.activeQuery = null;
  50352. }
  50353. }
  50354. /**
  50355. * Asynchronously resolves all completed queries and returns the total duration.
  50356. *
  50357. * @async
  50358. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  50359. */
  50360. async resolveQueriesAsync() {
  50361. if ( ! this.trackTimestamp || this.pendingResolve ) {
  50362. return this.lastValue;
  50363. }
  50364. this.pendingResolve = true;
  50365. try {
  50366. // Wait for all ended queries to complete
  50367. const resolvePromises = new Map();
  50368. for ( const [ uid, baseOffset ] of this.queryOffsets ) {
  50369. const state = this.queryStates.get( baseOffset );
  50370. if ( state === 'ended' ) {
  50371. const query = this.queries[ baseOffset ];
  50372. resolvePromises.set( uid, this.resolveQuery( query ) );
  50373. }
  50374. }
  50375. if ( resolvePromises.size === 0 ) {
  50376. return this.lastValue;
  50377. }
  50378. //
  50379. const framesDuration = {};
  50380. const frames = [];
  50381. for ( const [ uid, promise ] of resolvePromises ) {
  50382. const match = uid.match( /^(.*):f(\d+)$/ );
  50383. const frame = parseInt( match[ 2 ] );
  50384. if ( frames.includes( frame ) === false ) {
  50385. frames.push( frame );
  50386. }
  50387. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  50388. const duration = await promise;
  50389. this.timestamps.set( uid, duration );
  50390. framesDuration[ frame ] += duration;
  50391. }
  50392. // Return the total duration of the last frame
  50393. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  50394. // Store the last valid result
  50395. this.lastValue = totalDuration;
  50396. this.frames = frames;
  50397. // Reset states
  50398. this.currentQueryIndex = 0;
  50399. this.queryOffsets.clear();
  50400. this.queryStates.clear();
  50401. this.activeQuery = null;
  50402. return totalDuration;
  50403. } catch ( e ) {
  50404. error( 'Error resolving queries:', e );
  50405. return this.lastValue;
  50406. } finally {
  50407. this.pendingResolve = false;
  50408. }
  50409. }
  50410. /**
  50411. * Resolves a single query, checking for completion and disjoint operation.
  50412. *
  50413. * @async
  50414. * @param {WebGLQuery} query - The query object to resolve.
  50415. * @returns {Promise<number>} The elapsed time in milliseconds.
  50416. */
  50417. async resolveQuery( query ) {
  50418. return new Promise( ( resolve ) => {
  50419. if ( this.isDisposed ) {
  50420. resolve( this.lastValue );
  50421. return;
  50422. }
  50423. let timeoutId;
  50424. let isResolved = false;
  50425. const cleanup = () => {
  50426. if ( timeoutId ) {
  50427. clearTimeout( timeoutId );
  50428. timeoutId = null;
  50429. }
  50430. };
  50431. const finalizeResolution = ( value ) => {
  50432. if ( ! isResolved ) {
  50433. isResolved = true;
  50434. cleanup();
  50435. resolve( value );
  50436. }
  50437. };
  50438. const checkQuery = () => {
  50439. if ( this.isDisposed ) {
  50440. finalizeResolution( this.lastValue );
  50441. return;
  50442. }
  50443. try {
  50444. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  50445. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  50446. if ( disjoint ) {
  50447. finalizeResolution( this.lastValue );
  50448. return;
  50449. }
  50450. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  50451. if ( ! available ) {
  50452. timeoutId = setTimeout( checkQuery, 1 );
  50453. return;
  50454. }
  50455. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  50456. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  50457. } catch ( e ) {
  50458. error( 'Error checking query:', e );
  50459. resolve( this.lastValue );
  50460. }
  50461. };
  50462. checkQuery();
  50463. } );
  50464. }
  50465. /**
  50466. * Releases all resources held by this query pool.
  50467. * This includes deleting all query objects and clearing internal state.
  50468. */
  50469. dispose() {
  50470. if ( this.isDisposed ) {
  50471. return;
  50472. }
  50473. this.isDisposed = true;
  50474. if ( ! this.trackTimestamp ) return;
  50475. for ( const query of this.queries ) {
  50476. this.gl.deleteQuery( query );
  50477. }
  50478. this.queries = [];
  50479. this.queryStates.clear();
  50480. this.queryOffsets.clear();
  50481. this.lastValue = 0;
  50482. this.activeQuery = null;
  50483. }
  50484. }
  50485. /**
  50486. * A backend implementation targeting WebGL 2.
  50487. *
  50488. * @private
  50489. * @augments Backend
  50490. */
  50491. class WebGLBackend extends Backend {
  50492. /**
  50493. * WebGLBackend options.
  50494. *
  50495. * @typedef {Object} WebGLBackend~Options
  50496. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  50497. * @property {boolean} [reversedDepthBuffer=false] - Whether reversed depth buffer is enabled or not.
  50498. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  50499. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  50500. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  50501. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  50502. * @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.
  50503. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  50504. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  50505. */
  50506. /**
  50507. * Constructs a new WebGPU backend.
  50508. *
  50509. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  50510. */
  50511. constructor( parameters = {} ) {
  50512. super( parameters );
  50513. /**
  50514. * This flag can be used for type testing.
  50515. *
  50516. * @type {boolean}
  50517. * @readonly
  50518. * @default true
  50519. */
  50520. this.isWebGLBackend = true;
  50521. /**
  50522. * A reference to a backend module holding shader attribute-related
  50523. * utility functions.
  50524. *
  50525. * @type {?WebGLAttributeUtils}
  50526. * @default null
  50527. */
  50528. this.attributeUtils = null;
  50529. /**
  50530. * A reference to a backend module holding extension-related
  50531. * utility functions.
  50532. *
  50533. * @type {?WebGLExtensions}
  50534. * @default null
  50535. */
  50536. this.extensions = null;
  50537. /**
  50538. * A reference to a backend module holding capability-related
  50539. * utility functions.
  50540. *
  50541. * @type {?WebGLCapabilities}
  50542. * @default null
  50543. */
  50544. this.capabilities = null;
  50545. /**
  50546. * A reference to a backend module holding texture-related
  50547. * utility functions.
  50548. *
  50549. * @type {?WebGLTextureUtils}
  50550. * @default null
  50551. */
  50552. this.textureUtils = null;
  50553. /**
  50554. * A reference to a backend module holding renderer-related
  50555. * utility functions.
  50556. *
  50557. * @type {?WebGLBufferRenderer}
  50558. * @default null
  50559. */
  50560. this.bufferRenderer = null;
  50561. /**
  50562. * A reference to the rendering context.
  50563. *
  50564. * @type {?WebGL2RenderingContext}
  50565. * @default null
  50566. */
  50567. this.gl = null;
  50568. /**
  50569. * A reference to a backend module holding state-related
  50570. * utility functions.
  50571. *
  50572. * @type {?WebGLState}
  50573. * @default null
  50574. */
  50575. this.state = null;
  50576. /**
  50577. * A reference to a backend module holding common
  50578. * utility functions.
  50579. *
  50580. * @type {?WebGLUtils}
  50581. * @default null
  50582. */
  50583. this.utils = null;
  50584. /**
  50585. * Dictionary for caching VAOs.
  50586. *
  50587. * @type {Object<string,WebGLVertexArrayObject>}
  50588. */
  50589. this.vaoCache = {};
  50590. /**
  50591. * Dictionary for caching transform feedback objects.
  50592. *
  50593. * @type {Object<string,WebGLTransformFeedback>}
  50594. */
  50595. this.transformFeedbackCache = {};
  50596. /**
  50597. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  50598. * Only relevant when using compute shaders.
  50599. *
  50600. * @type {boolean}
  50601. * @default false
  50602. */
  50603. this.discard = false;
  50604. /**
  50605. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  50606. * device does not support the extension.
  50607. *
  50608. * @type {?EXTDisjointTimerQueryWebGL2}
  50609. * @default null
  50610. */
  50611. this.disjoint = null;
  50612. /**
  50613. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  50614. * device does not support the extension.
  50615. *
  50616. * @type {?KHRParallelShaderCompile}
  50617. * @default null
  50618. */
  50619. this.parallel = null;
  50620. /**
  50621. * A reference to the current render context.
  50622. *
  50623. * @private
  50624. * @type {RenderContext}
  50625. * @default null
  50626. */
  50627. this._currentContext = null;
  50628. /**
  50629. * A unique collection of bindings.
  50630. *
  50631. * @private
  50632. * @type {WeakSet<Array<BindGroup>>}
  50633. */
  50634. this._knownBindings = new WeakSet();
  50635. /**
  50636. * Whether the device supports framebuffers invalidation or not.
  50637. *
  50638. * @private
  50639. * @type {boolean}
  50640. */
  50641. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  50642. /**
  50643. * The target framebuffer when rendering with
  50644. * the WebXR device API.
  50645. *
  50646. * @private
  50647. * @type {?WebGLFramebuffer}
  50648. * @default null
  50649. */
  50650. this._xrFramebuffer = null;
  50651. }
  50652. /**
  50653. * Initializes the backend so it is ready for usage.
  50654. *
  50655. * @param {Renderer} renderer - The renderer.
  50656. */
  50657. init( renderer ) {
  50658. super.init( renderer );
  50659. //
  50660. const parameters = this.parameters;
  50661. const contextAttributes = {
  50662. antialias: renderer.currentSamples > 0,
  50663. alpha: true, // always true for performance reasons
  50664. depth: renderer.depth,
  50665. stencil: renderer.stencil
  50666. };
  50667. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  50668. function onContextLost( event ) {
  50669. event.preventDefault();
  50670. const contextLossInfo = {
  50671. api: 'WebGL',
  50672. message: event.statusMessage || 'Unknown reason',
  50673. reason: null,
  50674. originalEvent: event
  50675. };
  50676. renderer.onDeviceLost( contextLossInfo );
  50677. }
  50678. this._onContextLost = onContextLost;
  50679. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  50680. this.gl = glContext;
  50681. this.extensions = new WebGLExtensions( this );
  50682. this.capabilities = new WebGLCapabilities( this );
  50683. this.attributeUtils = new WebGLAttributeUtils( this );
  50684. this.textureUtils = new WebGLTextureUtils( this );
  50685. this.bufferRenderer = new WebGLBufferRenderer( this );
  50686. this.state = new WebGLState( this );
  50687. this.utils = new WebGLUtils( this );
  50688. this.extensions.get( 'EXT_color_buffer_float' );
  50689. this.extensions.get( 'WEBGL_clip_cull_distance' );
  50690. this.extensions.get( 'OES_texture_float_linear' );
  50691. this.extensions.get( 'EXT_color_buffer_half_float' );
  50692. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  50693. this.extensions.get( 'WEBGL_render_shared_exponent' );
  50694. this.extensions.get( 'WEBGL_multi_draw' );
  50695. this.extensions.get( 'OVR_multiview2' );
  50696. this.extensions.get( 'EXT_clip_control' );
  50697. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  50698. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  50699. this.drawBuffersIndexedExt = this.extensions.get( 'OES_draw_buffers_indexed' );
  50700. if ( parameters.reversedDepthBuffer ) {
  50701. if ( this.extensions.has( 'EXT_clip_control' ) ) {
  50702. renderer.reversedDepthBuffer = true;
  50703. } else {
  50704. warn( 'WebGPURenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.' );
  50705. renderer.reversedDepthBuffer = false;
  50706. }
  50707. }
  50708. if ( renderer.reversedDepthBuffer ) {
  50709. this.state.setReversedDepth( true );
  50710. }
  50711. }
  50712. /**
  50713. * The coordinate system of the backend.
  50714. *
  50715. * @type {number}
  50716. * @readonly
  50717. */
  50718. get coordinateSystem() {
  50719. return WebGLCoordinateSystem;
  50720. }
  50721. /**
  50722. * Whether the backend supports query timestamps or not.
  50723. *
  50724. * @type {boolean}
  50725. * @readonly
  50726. */
  50727. get hasTimestamp() {
  50728. return this.disjoint !== null;
  50729. }
  50730. /**
  50731. * This method performs a readback operation by moving buffer data from
  50732. * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can
  50733. * be used to retain and reuse handles to the intermediate buffers and prevent
  50734. * new allocation.
  50735. *
  50736. * @async
  50737. * @param {BufferAttribute} attribute - The storage buffer attribute to read frm.
  50738. * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute.
  50739. * @param {number} offset - The storage buffer attribute.
  50740. * @param {number} count - The offset from which to start reading the
  50741. * @return {Promise<ArrayBuffer|ReadbackBuffer>} A promise that resolves with the buffer data when the data are ready.
  50742. */
  50743. async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) {
  50744. return await this.attributeUtils.getArrayBufferAsync( attribute, target, offset, count );
  50745. }
  50746. /**
  50747. * Ensures the backend is XR compatible.
  50748. *
  50749. * @async
  50750. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  50751. */
  50752. async makeXRCompatible() {
  50753. const attributes = this.gl.getContextAttributes();
  50754. if ( attributes.xrCompatible !== true ) {
  50755. await this.gl.makeXRCompatible();
  50756. }
  50757. }
  50758. /**
  50759. * Sets the XR rendering destination.
  50760. *
  50761. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  50762. */
  50763. setXRTarget( xrFramebuffer ) {
  50764. this._xrFramebuffer = xrFramebuffer;
  50765. }
  50766. /**
  50767. * Configures the given XR render target with external textures.
  50768. *
  50769. * This method is only relevant when using the WebXR Layers API.
  50770. *
  50771. * @param {XRRenderTarget} renderTarget - The XR render target.
  50772. * @param {WebGLTexture} colorTexture - A native color texture.
  50773. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  50774. */
  50775. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  50776. const gl = this.gl;
  50777. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  50778. if ( depthTexture !== null ) {
  50779. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  50780. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  50781. // The multisample_render_to_texture extension doesn't work properly if there
  50782. // are midframe flushes and an external depth texture.
  50783. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  50784. warn( 'WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  50785. }
  50786. renderTarget._autoAllocateDepthBuffer = false;
  50787. }
  50788. }
  50789. /**
  50790. * Inits a time stamp query for the given render context.
  50791. *
  50792. * @param {string} type - The type of the timestamp query.
  50793. * @param {string} uid - A unique identifier for the timestamp query.
  50794. */
  50795. initTimestampQuery( type, uid ) {
  50796. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  50797. if ( ! this.timestampQueryPool[ type ] ) {
  50798. // TODO: Variable maxQueries?
  50799. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  50800. }
  50801. const timestampQueryPool = this.timestampQueryPool[ type ];
  50802. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  50803. if ( baseOffset !== null ) {
  50804. timestampQueryPool.beginQuery( uid );
  50805. }
  50806. }
  50807. // timestamp utils
  50808. /**
  50809. * Prepares the timestamp buffer.
  50810. *
  50811. * @param {string} type - The type of the timestamp query.
  50812. * @param {string} uid - A unique identifier for the timestamp query.
  50813. */
  50814. prepareTimestampBuffer( type, uid ) {
  50815. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  50816. const timestampQueryPool = this.timestampQueryPool[ type ];
  50817. timestampQueryPool.endQuery( uid );
  50818. }
  50819. /**
  50820. * Returns the backend's rendering context.
  50821. *
  50822. * @return {WebGL2RenderingContext} The rendering context.
  50823. */
  50824. getContext() {
  50825. return this.gl;
  50826. }
  50827. /**
  50828. * This method is executed at the beginning of a render call and prepares
  50829. * the WebGL state for upcoming render calls
  50830. *
  50831. * @param {RenderContext} renderContext - The render context.
  50832. */
  50833. beginRender( renderContext ) {
  50834. const { state } = this;
  50835. const renderContextData = this.get( renderContext );
  50836. //
  50837. if ( renderContext.viewport ) {
  50838. this.updateViewport( renderContext );
  50839. } else {
  50840. const { width, height } = this.getDrawingBufferSize();
  50841. state.viewport( 0, 0, width, height );
  50842. }
  50843. if ( renderContext.scissor ) {
  50844. this.updateScissor( renderContext );
  50845. } else {
  50846. const { width, height } = this.getDrawingBufferSize();
  50847. state.scissor( 0, 0, width, height );
  50848. }
  50849. //
  50850. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  50851. renderContextData.previousContext = this._currentContext;
  50852. this._currentContext = renderContext;
  50853. this._setFramebuffer( renderContext );
  50854. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  50855. const occlusionQueryCount = renderContext.occlusionQueryCount;
  50856. if ( occlusionQueryCount > 0 ) {
  50857. // Get a reference to the array of objects with queries. The renderContextData property
  50858. // can be changed by another render pass before the async reading of all previous queries complete
  50859. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  50860. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  50861. renderContextData.lastOcclusionObject = null;
  50862. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  50863. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  50864. renderContextData.occlusionQueryIndex = 0;
  50865. }
  50866. }
  50867. /**
  50868. * This method is executed at the end of a render call and finalizes work
  50869. * after draw calls.
  50870. *
  50871. * @param {RenderContext} renderContext - The render context.
  50872. */
  50873. finishRender( renderContext ) {
  50874. const { gl, state } = this;
  50875. const renderContextData = this.get( renderContext );
  50876. const previousContext = renderContextData.previousContext;
  50877. state.resetVertexState();
  50878. const occlusionQueryCount = renderContext.occlusionQueryCount;
  50879. if ( occlusionQueryCount > 0 ) {
  50880. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  50881. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  50882. }
  50883. this.resolveOccludedAsync( renderContext );
  50884. }
  50885. const textures = renderContext.textures;
  50886. if ( textures !== null ) {
  50887. for ( let i = 0; i < textures.length; i ++ ) {
  50888. const texture = textures[ i ];
  50889. if ( texture.generateMipmaps ) {
  50890. this.generateMipmaps( texture );
  50891. }
  50892. }
  50893. }
  50894. this._currentContext = previousContext;
  50895. this._resolveRenderTarget( renderContext );
  50896. if ( previousContext !== null ) {
  50897. this._setFramebuffer( previousContext );
  50898. if ( previousContext.viewport ) {
  50899. this.updateViewport( previousContext );
  50900. } else {
  50901. const { width, height } = this.getDrawingBufferSize();
  50902. state.viewport( 0, 0, width, height );
  50903. }
  50904. if ( previousContext.scissor ) {
  50905. this.updateScissor( previousContext );
  50906. } else {
  50907. const { width, height } = this.getDrawingBufferSize();
  50908. state.scissor( 0, 0, width, height );
  50909. }
  50910. }
  50911. this.prepareTimestampBuffer( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  50912. }
  50913. /**
  50914. * This method processes the result of occlusion queries and writes it
  50915. * into render context data.
  50916. *
  50917. * @async
  50918. * @param {RenderContext} renderContext - The render context.
  50919. */
  50920. resolveOccludedAsync( renderContext ) {
  50921. const renderContextData = this.get( renderContext );
  50922. // handle occlusion query results
  50923. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  50924. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  50925. const occluded = new WeakSet();
  50926. const { gl } = this;
  50927. renderContextData.currentOcclusionQueryObjects = null;
  50928. renderContextData.currentOcclusionQueries = null;
  50929. const check = () => {
  50930. let completed = 0;
  50931. // check all queries and requeue as appropriate
  50932. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  50933. const query = currentOcclusionQueries[ i ];
  50934. if ( query === null ) continue;
  50935. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  50936. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  50937. currentOcclusionQueries[ i ] = null;
  50938. gl.deleteQuery( query );
  50939. completed ++;
  50940. }
  50941. }
  50942. if ( completed < currentOcclusionQueries.length ) {
  50943. requestAnimationFrame( check );
  50944. } else {
  50945. renderContextData.occluded = occluded;
  50946. }
  50947. };
  50948. check();
  50949. }
  50950. }
  50951. /**
  50952. * Returns `true` if the given 3D object is fully occluded by other
  50953. * 3D objects in the scene.
  50954. *
  50955. * @param {RenderContext} renderContext - The render context.
  50956. * @param {Object3D} object - The 3D object to test.
  50957. * @return {boolean} Whether the 3D object is fully occluded or not.
  50958. */
  50959. isOccluded( renderContext, object ) {
  50960. const renderContextData = this.get( renderContext );
  50961. return renderContextData.occluded && renderContextData.occluded.has( object );
  50962. }
  50963. /**
  50964. * Updates the viewport with the values from the given render context.
  50965. *
  50966. * @param {RenderContext} renderContext - The render context.
  50967. */
  50968. updateViewport( renderContext ) {
  50969. const { state } = this;
  50970. const { x, y, width, height } = renderContext.viewportValue;
  50971. state.viewport( x, renderContext.height - height - y, width, height );
  50972. }
  50973. /**
  50974. * Updates the scissor with the values from the given render context.
  50975. *
  50976. * @param {RenderContext} renderContext - The render context.
  50977. */
  50978. updateScissor( renderContext ) {
  50979. const { state } = this;
  50980. const { x, y, width, height } = renderContext.scissorValue;
  50981. state.scissor( x, renderContext.height - height - y, width, height );
  50982. }
  50983. /**
  50984. * Defines the scissor test.
  50985. *
  50986. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  50987. */
  50988. setScissorTest( boolean ) {
  50989. const state = this.state;
  50990. state.setScissorTest( boolean );
  50991. }
  50992. /**
  50993. * Returns the clear color and alpha into a single
  50994. * color object.
  50995. *
  50996. * @return {Color4} The clear color.
  50997. */
  50998. getClearColor() {
  50999. const clearColor = super.getClearColor();
  51000. // Since the canvas is always created with alpha: true,
  51001. // WebGL must always premultiply the clear color.
  51002. clearColor.r *= clearColor.a;
  51003. clearColor.g *= clearColor.a;
  51004. clearColor.b *= clearColor.a;
  51005. return clearColor;
  51006. }
  51007. /**
  51008. * Performs a clear operation.
  51009. *
  51010. * @param {boolean} color - Whether the color buffer should be cleared or not.
  51011. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  51012. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  51013. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  51014. * @param {boolean} [setFrameBuffer=true] - Controls whether the intermediate framebuffer should be set or not.
  51015. * @param {boolean} [resolveRenderTarget=true] - Controls whether an active render target should be resolved
  51016. * or not. Only relevant for explicit clears.
  51017. */
  51018. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true, resolveRenderTarget = true ) {
  51019. const { gl, renderer } = this;
  51020. if ( descriptor === null ) {
  51021. const clearColor = this.getClearColor();
  51022. descriptor = {
  51023. textures: null,
  51024. clearColorValue: clearColor
  51025. };
  51026. }
  51027. //
  51028. let clear = 0;
  51029. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  51030. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  51031. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  51032. if ( clear !== 0 ) {
  51033. let clearColor;
  51034. if ( descriptor.clearColorValue ) {
  51035. clearColor = descriptor.clearColorValue;
  51036. } else {
  51037. clearColor = this.getClearColor();
  51038. }
  51039. const clearDepth = renderer.getClearDepth();
  51040. const clearStencil = renderer.getClearStencil();
  51041. if ( depth ) this.state.setDepthMask( true );
  51042. if ( descriptor.textures === null ) {
  51043. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  51044. gl.clear( clear );
  51045. } else {
  51046. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  51047. if ( color ) {
  51048. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  51049. if ( i === 0 ) {
  51050. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  51051. } else {
  51052. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  51053. }
  51054. }
  51055. }
  51056. if ( depth && stencil ) {
  51057. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  51058. } else if ( depth ) {
  51059. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  51060. } else if ( stencil ) {
  51061. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  51062. }
  51063. if ( setFrameBuffer && resolveRenderTarget ) this._resolveRenderTarget( descriptor );
  51064. // Restore the framebuffer of the active render pass when clearing an unrelated
  51065. // render target, so subsequent draws in the pass don't bind to the cleared target.
  51066. if ( setFrameBuffer && this._currentContext !== null && this._currentContext !== descriptor ) {
  51067. this._setFramebuffer( this._currentContext );
  51068. }
  51069. }
  51070. }
  51071. }
  51072. /**
  51073. * This method is executed at the beginning of a compute call and
  51074. * prepares the state for upcoming compute tasks.
  51075. *
  51076. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  51077. */
  51078. beginCompute( computeGroup ) {
  51079. const { state, gl } = this;
  51080. //
  51081. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  51082. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  51083. }
  51084. /**
  51085. * Executes a compute command for the given compute node.
  51086. *
  51087. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  51088. * @param {Node} computeNode - The compute node.
  51089. * @param {Array<BindGroup>} bindings - The bindings.
  51090. * @param {ComputePipeline} pipeline - The compute pipeline.
  51091. * @param {?number} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  51092. */
  51093. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  51094. const { state, gl } = this;
  51095. if ( this.discard === false ) {
  51096. // required here to handle async behaviour of render.compute()
  51097. state.enable( gl.RASTERIZER_DISCARD );
  51098. this.discard = true;
  51099. }
  51100. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  51101. const vaoKey = this._getVaoKey( attributes );
  51102. const vaoGPU = this.vaoCache[ vaoKey ];
  51103. if ( vaoGPU === undefined ) {
  51104. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  51105. } else {
  51106. state.setVertexState( vaoGPU );
  51107. }
  51108. state.useProgram( programGPU );
  51109. this._bindUniforms( bindings );
  51110. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  51111. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  51112. gl.beginTransformFeedback( gl.POINTS );
  51113. count = ( count !== null ) ? count : computeNode.count;
  51114. if ( Array.isArray( count ) ) {
  51115. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  51116. count = count[ 0 ];
  51117. } else if ( count && typeof count === 'object' && count.isIndirectStorageBufferAttribute ) {
  51118. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute' );
  51119. count = computeNode.count;
  51120. }
  51121. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  51122. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  51123. } else {
  51124. gl.drawArrays( gl.POINTS, 0, count );
  51125. }
  51126. gl.endTransformFeedback();
  51127. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  51128. // switch active buffers
  51129. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  51130. const dualAttributeData = transformBuffers[ i ];
  51131. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  51132. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  51133. }
  51134. dualAttributeData.switchBuffers();
  51135. }
  51136. }
  51137. /**
  51138. * This method is executed at the end of a compute call and
  51139. * finalizes work after compute tasks.
  51140. *
  51141. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  51142. */
  51143. finishCompute( computeGroup ) {
  51144. const { state, gl } = this;
  51145. this.discard = false;
  51146. state.disable( gl.RASTERIZER_DISCARD );
  51147. this.prepareTimestampBuffer( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  51148. if ( this._currentContext ) {
  51149. this._setFramebuffer( this._currentContext );
  51150. }
  51151. }
  51152. /**
  51153. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  51154. *
  51155. * @param {RenderContext} renderContext - The render context.
  51156. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  51157. *
  51158. * @private
  51159. */
  51160. _isRenderCameraDepthArray( renderContext ) {
  51161. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  51162. }
  51163. /**
  51164. * Internal draw function.
  51165. *
  51166. * @private
  51167. * @param {Object3D} object - The object to render.
  51168. * @param {WebGLBufferRenderer} renderer - The internal renderer.
  51169. * @param {number} firstVertex - The first vertex to render.
  51170. * @param {number} vertexCount - The vertex count.
  51171. * @param {number} instanceCount - The intance count.
  51172. * @param {WebGLProgram} programGPU - The raw WebGL shader program.
  51173. */
  51174. _draw( object, renderer, firstVertex, vertexCount, instanceCount, programGPU ) {
  51175. if ( object.isBatchedMesh ) {
  51176. if ( this.hasFeature( 'WEBGL_multi_draw' ) === false ) {
  51177. const { gl } = this;
  51178. const drawIdLocation = gl.getUniformLocation( programGPU, 'nodeUniformDrawId' );
  51179. const starts = object._multiDrawStarts;
  51180. const counts = object._multiDrawCounts;
  51181. const drawCount = object._multiDrawCount;
  51182. for ( let i = 0; i < drawCount; i ++ ) {
  51183. gl.uniform1ui( drawIdLocation, i );
  51184. renderer.render( starts[ i ], counts[ i ] );
  51185. }
  51186. } else {
  51187. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  51188. }
  51189. } else if ( instanceCount > 1 ) {
  51190. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  51191. } else {
  51192. renderer.render( firstVertex, vertexCount );
  51193. }
  51194. }
  51195. /**
  51196. * Executes a draw command for the given render object.
  51197. *
  51198. * @param {RenderObject} renderObject - The render object to draw.
  51199. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  51200. */
  51201. draw( renderObject/*, info*/ ) {
  51202. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  51203. const { programGPU } = this.get( pipeline );
  51204. const { gl, state } = this;
  51205. const contextData = this.get( context );
  51206. const drawParams = renderObject.getDrawParameters();
  51207. if ( drawParams === null ) return;
  51208. //
  51209. this._bindUniforms( renderObject.getBindings() );
  51210. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  51211. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  51212. if ( context.mrt !== null && context.textures !== null ) {
  51213. state.setMRTBlending( context.textures, context.mrt, material );
  51214. }
  51215. state.useProgram( programGPU );
  51216. // vertex state
  51217. const attributes = renderObject.getAttributes();
  51218. const attributesData = this.get( attributes );
  51219. let vaoGPU = attributesData.vaoGPU;
  51220. if ( vaoGPU === undefined ) {
  51221. const vaoKey = this._getVaoKey( attributes );
  51222. vaoGPU = this.vaoCache[ vaoKey ];
  51223. if ( vaoGPU === undefined ) {
  51224. vaoGPU = this._createVao( attributes );
  51225. this.vaoCache[ vaoKey ] = vaoGPU;
  51226. attributesData.vaoGPU = vaoGPU;
  51227. }
  51228. }
  51229. const index = renderObject.getIndex();
  51230. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  51231. state.setVertexState( vaoGPU, indexGPU );
  51232. //
  51233. const lastObject = contextData.lastOcclusionObject;
  51234. if ( lastObject !== object && lastObject !== undefined ) {
  51235. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  51236. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  51237. contextData.occlusionQueryIndex ++;
  51238. }
  51239. if ( object.occlusionTest === true ) {
  51240. const query = gl.createQuery();
  51241. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  51242. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  51243. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  51244. }
  51245. contextData.lastOcclusionObject = object;
  51246. }
  51247. //
  51248. const renderer = this.bufferRenderer;
  51249. if ( object.isPoints ) renderer.mode = gl.POINTS;
  51250. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  51251. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  51252. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  51253. else {
  51254. if ( material.wireframe === true ) {
  51255. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  51256. renderer.mode = gl.LINES;
  51257. } else {
  51258. renderer.mode = gl.TRIANGLES;
  51259. }
  51260. }
  51261. //
  51262. const { vertexCount, instanceCount } = drawParams;
  51263. let { firstVertex } = drawParams;
  51264. renderer.object = object;
  51265. if ( index !== null ) {
  51266. firstVertex *= index.array.BYTES_PER_ELEMENT;
  51267. const indexData = this.get( index );
  51268. renderer.index = index.count;
  51269. renderer.type = indexData.type;
  51270. } else {
  51271. renderer.index = 0;
  51272. }
  51273. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  51274. const cameraData = this.get( renderObject.camera );
  51275. const cameras = renderObject.camera.cameras;
  51276. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  51277. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  51278. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  51279. const indexesGPU = [];
  51280. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  51281. const bufferGPU = gl.createBuffer();
  51282. data[ 0 ] = i;
  51283. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  51284. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  51285. indexesGPU.push( bufferGPU );
  51286. }
  51287. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  51288. }
  51289. let cameraIndexBufferIndex = 0;
  51290. bindingsSearch: for ( const bindGroup of renderObject.getBindings() ) {
  51291. for ( const binding of bindGroup.bindings ) {
  51292. if ( binding === cameraIndex ) break bindingsSearch;
  51293. if ( binding.isUniformsGroup || binding.isUniformBuffer ) cameraIndexBufferIndex ++;
  51294. }
  51295. }
  51296. const pixelRatio = this.renderer.getPixelRatio();
  51297. const renderTarget = this._currentContext.renderTarget;
  51298. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  51299. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  51300. if ( isRenderCameraDepthArray ) {
  51301. // Clear the depth texture
  51302. const textureData = this.get( renderTarget.depthTexture );
  51303. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  51304. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  51305. const { stencilBuffer } = renderTarget;
  51306. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  51307. this.renderer._activeCubeFace = i;
  51308. this._currentContext.activeCubeFace = i;
  51309. this._setFramebuffer( this._currentContext );
  51310. this.clear( false, true, stencilBuffer, this._currentContext, false, false );
  51311. }
  51312. this.renderer._activeCubeFace = prevActiveCubeFace;
  51313. this._currentContext.activeCubeFace = prevActiveCubeFace;
  51314. }
  51315. }
  51316. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  51317. const subCamera = cameras[ i ];
  51318. if ( object.layers.test( subCamera.layers ) ) {
  51319. if ( isRenderCameraDepthArray ) {
  51320. // Update the active layer
  51321. this.renderer._activeCubeFace = i;
  51322. this._currentContext.activeCubeFace = i;
  51323. this._setFramebuffer( this._currentContext );
  51324. }
  51325. const vp = subCamera.viewport;
  51326. if ( vp !== undefined ) {
  51327. const x = vp.x * pixelRatio;
  51328. const y = vp.y * pixelRatio;
  51329. const width = vp.width * pixelRatio;
  51330. const height = vp.height * pixelRatio;
  51331. state.viewport(
  51332. Math.floor( x ),
  51333. Math.floor( renderObject.context.height - height - y ),
  51334. Math.floor( width ),
  51335. Math.floor( height )
  51336. );
  51337. }
  51338. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexBufferIndex, cameraData.indexesGPU[ i ] );
  51339. this._draw( object, renderer, firstVertex, vertexCount, instanceCount, programGPU );
  51340. }
  51341. this._currentContext.activeCubeFace = prevActiveCubeFace;
  51342. this.renderer._activeCubeFace = prevActiveCubeFace;
  51343. }
  51344. } else {
  51345. this._draw( object, renderer, firstVertex, vertexCount, instanceCount, programGPU );
  51346. }
  51347. }
  51348. /**
  51349. * Explain why always null is returned.
  51350. *
  51351. * @param {RenderObject} renderObject - The render object.
  51352. * @return {boolean} Whether the render pipeline requires an update or not.
  51353. */
  51354. needsRenderUpdate( /*renderObject*/ ) {
  51355. return false;
  51356. }
  51357. /**
  51358. * Explain why no cache key is computed.
  51359. *
  51360. * @param {RenderObject} renderObject - The render object.
  51361. * @return {string} The cache key.
  51362. */
  51363. getRenderCacheKey( /*renderObject*/ ) {
  51364. return '';
  51365. }
  51366. // textures
  51367. /**
  51368. * Creates a default texture for the given texture that can be used
  51369. * as a placeholder until the actual texture is ready for usage.
  51370. *
  51371. * @param {Texture} texture - The texture to create a default texture for.
  51372. */
  51373. createDefaultTexture( texture ) {
  51374. this.textureUtils.createDefaultTexture( texture );
  51375. }
  51376. /**
  51377. * Defines a texture on the GPU for the given texture object.
  51378. *
  51379. * @param {Texture} texture - The texture.
  51380. * @param {Object} [options={}] - Optional configuration parameter.
  51381. */
  51382. createTexture( texture, options ) {
  51383. this.textureUtils.createTexture( texture, options );
  51384. }
  51385. /**
  51386. * Uploads the updated texture data to the GPU.
  51387. *
  51388. * @param {Texture} texture - The texture.
  51389. * @param {Object} [options={}] - Optional configuration parameter.
  51390. */
  51391. updateTexture( texture, options ) {
  51392. this.textureUtils.updateTexture( texture, options );
  51393. }
  51394. /**
  51395. * Generates mipmaps for the given texture.
  51396. *
  51397. * @param {Texture} texture - The texture.
  51398. */
  51399. generateMipmaps( texture ) {
  51400. this.textureUtils.generateMipmaps( texture );
  51401. }
  51402. /**
  51403. * Destroys the GPU data for the given texture object.
  51404. *
  51405. * @param {Texture} texture - The texture.
  51406. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  51407. */
  51408. destroyTexture( texture, isDefaultTexture = false ) {
  51409. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  51410. }
  51411. /**
  51412. * Returns texture data as a typed array.
  51413. *
  51414. * @async
  51415. * @param {Texture} texture - The texture to copy.
  51416. * @param {number} x - The x coordinate of the copy origin.
  51417. * @param {number} y - The y coordinate of the copy origin.
  51418. * @param {number} width - The width of the copy.
  51419. * @param {number} height - The height of the copy.
  51420. * @param {number} faceIndex - The face index.
  51421. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  51422. */
  51423. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  51424. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  51425. }
  51426. /**
  51427. * This method does nothing since WebGL 2 has no concept of samplers.
  51428. *
  51429. * @param {Texture} texture - The texture to update the sampler for.
  51430. * @param {TextureNode} textureNode - The texture node to update the sampler with.
  51431. * @return {string} The current sampler key.
  51432. */
  51433. updateSampler( /*texture, textureNode*/ ) {
  51434. return '';
  51435. }
  51436. // node builder
  51437. /**
  51438. * Returns a node builder for the given render object.
  51439. *
  51440. * @param {RenderObject} object - The render object.
  51441. * @param {Renderer} renderer - The renderer.
  51442. * @return {GLSLNodeBuilder} The node builder.
  51443. */
  51444. createNodeBuilder( object, renderer ) {
  51445. return new GLSLNodeBuilder( object, renderer );
  51446. }
  51447. // program
  51448. /**
  51449. * Creates a shader program from the given programmable stage.
  51450. *
  51451. * @param {ProgrammableStage} program - The programmable stage.
  51452. */
  51453. createProgram( program ) {
  51454. const gl = this.gl;
  51455. const { stage, code } = program;
  51456. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  51457. gl.shaderSource( shader, code );
  51458. gl.compileShader( shader );
  51459. this.set( program, {
  51460. shaderGPU: shader
  51461. } );
  51462. }
  51463. /**
  51464. * Destroys the shader program of the given programmable stage.
  51465. *
  51466. * @param {ProgrammableStage} program - The programmable stage.
  51467. */
  51468. destroyProgram( program ) {
  51469. this.delete( program );
  51470. }
  51471. /**
  51472. * Creates a render pipeline for the given render object.
  51473. *
  51474. * @param {RenderObject} renderObject - The render object.
  51475. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  51476. */
  51477. createRenderPipeline( renderObject, promises ) {
  51478. const gl = this.gl;
  51479. const pipeline = renderObject.pipeline;
  51480. // Program
  51481. const { fragmentProgram, vertexProgram } = pipeline;
  51482. const programGPU = gl.createProgram();
  51483. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  51484. const vertexShader = this.get( vertexProgram ).shaderGPU;
  51485. gl.attachShader( programGPU, fragmentShader );
  51486. gl.attachShader( programGPU, vertexShader );
  51487. gl.linkProgram( programGPU );
  51488. this.set( pipeline, {
  51489. programGPU,
  51490. fragmentShader,
  51491. vertexShader
  51492. } );
  51493. if ( promises !== null && this.parallel ) {
  51494. const p = new Promise( ( resolve /*, reject*/ ) => {
  51495. const parallel = this.parallel;
  51496. const checkStatus = () => {
  51497. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  51498. this._completeCompile( renderObject, pipeline );
  51499. resolve();
  51500. } else {
  51501. requestAnimationFrame( checkStatus );
  51502. }
  51503. };
  51504. checkStatus();
  51505. } );
  51506. promises.push( p );
  51507. return;
  51508. }
  51509. this._completeCompile( renderObject, pipeline );
  51510. }
  51511. /**
  51512. * Formats the source code of error messages.
  51513. *
  51514. * @private
  51515. * @param {string} string - The code.
  51516. * @param {number} errorLine - The error line.
  51517. * @return {string} The formatted code.
  51518. */
  51519. _handleSource( string, errorLine ) {
  51520. const lines = string.split( '\n' );
  51521. const lines2 = [];
  51522. const from = Math.max( errorLine - 6, 0 );
  51523. const to = Math.min( errorLine + 6, lines.length );
  51524. for ( let i = from; i < to; i ++ ) {
  51525. const line = i + 1;
  51526. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  51527. }
  51528. return lines2.join( '\n' );
  51529. }
  51530. /**
  51531. * Gets the shader compilation errors from the info log.
  51532. *
  51533. * @private
  51534. * @param {WebGL2RenderingContext} gl - The rendering context.
  51535. * @param {WebGLShader} shader - The WebGL shader object.
  51536. * @param {string} type - The shader type.
  51537. * @return {string} The shader errors.
  51538. */
  51539. _getShaderErrors( gl, shader, type ) {
  51540. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  51541. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  51542. const errors = shaderInfoLog.trim();
  51543. if ( status && errors === '' ) return '';
  51544. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  51545. if ( errorMatches ) {
  51546. const errorLine = parseInt( errorMatches[ 1 ] );
  51547. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  51548. } else {
  51549. return errors;
  51550. }
  51551. }
  51552. /**
  51553. * Logs shader compilation errors.
  51554. *
  51555. * @private
  51556. * @param {WebGLProgram} programGPU - The WebGL program.
  51557. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  51558. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  51559. */
  51560. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  51561. if ( this.renderer.debug.checkShaderErrors ) {
  51562. const gl = this.gl;
  51563. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  51564. const programLog = programInfoLog.trim();
  51565. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  51566. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  51567. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  51568. } else {
  51569. // default error reporting
  51570. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  51571. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  51572. error(
  51573. 'WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  51574. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  51575. 'Program Info Log: ' + programLog + '\n' +
  51576. vertexErrors + '\n' +
  51577. fragmentErrors
  51578. );
  51579. }
  51580. } else if ( programLog !== '' ) {
  51581. warn( 'WebGLProgram: Program Info Log:', programLog );
  51582. }
  51583. }
  51584. }
  51585. /**
  51586. * Completes the shader program setup for the given render object.
  51587. *
  51588. * @private
  51589. * @param {RenderObject} renderObject - The render object.
  51590. * @param {RenderPipeline} pipeline - The render pipeline.
  51591. */
  51592. _completeCompile( renderObject, pipeline ) {
  51593. const { state, gl } = this;
  51594. const pipelineData = this.get( pipeline );
  51595. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  51596. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  51597. this._logProgramError( programGPU, fragmentShader, vertexShader );
  51598. }
  51599. state.useProgram( programGPU );
  51600. // Bindings
  51601. const bindings = renderObject.getBindings();
  51602. this._setupBindings( bindings, programGPU );
  51603. //
  51604. this.set( pipeline, {
  51605. programGPU,
  51606. pipeline: programGPU
  51607. } );
  51608. }
  51609. /**
  51610. * Creates a compute pipeline for the given compute node.
  51611. *
  51612. * @param {ComputePipeline} computePipeline - The compute pipeline.
  51613. * @param {Array<BindGroup>} bindings - The bindings.
  51614. */
  51615. createComputePipeline( computePipeline, bindings ) {
  51616. const { state, gl } = this;
  51617. // Program
  51618. const fragmentProgram = {
  51619. stage: 'fragment',
  51620. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  51621. };
  51622. this.createProgram( fragmentProgram );
  51623. const { computeProgram } = computePipeline;
  51624. const programGPU = gl.createProgram();
  51625. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  51626. const vertexShader = this.get( computeProgram ).shaderGPU;
  51627. const transforms = computeProgram.transforms;
  51628. const transformVaryingNames = [];
  51629. const transformAttributeNodes = [];
  51630. for ( let i = 0; i < transforms.length; i ++ ) {
  51631. const transform = transforms[ i ];
  51632. transformVaryingNames.push( transform.varyingName );
  51633. transformAttributeNodes.push( transform.attributeNode );
  51634. }
  51635. gl.attachShader( programGPU, fragmentShader );
  51636. gl.attachShader( programGPU, vertexShader );
  51637. gl.transformFeedbackVaryings(
  51638. programGPU,
  51639. transformVaryingNames,
  51640. gl.SEPARATE_ATTRIBS
  51641. );
  51642. gl.linkProgram( programGPU );
  51643. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  51644. this._logProgramError( programGPU, fragmentShader, vertexShader );
  51645. }
  51646. state.useProgram( programGPU );
  51647. // Bindings
  51648. this._setupBindings( bindings, programGPU );
  51649. const attributeNodes = computeProgram.attributes;
  51650. const attributes = [];
  51651. const transformBuffers = [];
  51652. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  51653. const attribute = attributeNodes[ i ].node.attribute;
  51654. attributes.push( attribute );
  51655. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  51656. }
  51657. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  51658. const attribute = transformAttributeNodes[ i ].attribute;
  51659. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  51660. const attributeData = this.get( attribute );
  51661. transformBuffers.push( attributeData );
  51662. }
  51663. //
  51664. this.set( computePipeline, {
  51665. programGPU,
  51666. transformBuffers,
  51667. attributes
  51668. } );
  51669. }
  51670. /**
  51671. * Creates bindings from the given bind group definition.
  51672. *
  51673. * @param {BindGroup} bindGroup - The bind group.
  51674. * @param {Array<BindGroup>} bindings - Array of bind groups.
  51675. * @param {number} cacheIndex - The cache index.
  51676. * @param {number} version - The version.
  51677. */
  51678. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  51679. if ( this._knownBindings.has( bindings ) === false ) {
  51680. this._knownBindings.add( bindings );
  51681. let uniformBuffers = 0;
  51682. let textures = 0;
  51683. for ( const bindGroup of bindings ) {
  51684. this.set( bindGroup, {
  51685. textures: textures,
  51686. uniformBuffers: uniformBuffers
  51687. } );
  51688. for ( const binding of bindGroup.bindings ) {
  51689. if ( binding.isUniformBuffer ) uniformBuffers ++;
  51690. if ( binding.isSampledTexture ) textures ++;
  51691. }
  51692. }
  51693. }
  51694. this.updateBindings( bindGroup, bindings );
  51695. }
  51696. /**
  51697. * Updates the given bind group definition.
  51698. *
  51699. * @param {BindGroup} bindGroup - The bind group.
  51700. * @param {Array<BindGroup>} bindings - Array of bind groups.
  51701. * @param {number} cacheIndex - The cache index.
  51702. * @param {number} version - The version.
  51703. */
  51704. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  51705. const { gl } = this;
  51706. for ( const binding of bindGroup.bindings ) {
  51707. const map = this.get( binding );
  51708. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  51709. const array = binding.buffer;
  51710. const bufferGPU = map.bufferGPU;
  51711. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  51712. // update
  51713. const updateRanges = binding.updateRanges;
  51714. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  51715. if ( updateRanges.length === 0 ) {
  51716. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  51717. } else {
  51718. const isTyped = isTypedArray( array );
  51719. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  51720. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  51721. const range = updateRanges[ i ];
  51722. const dataOffset = range.start * byteOffsetFactor;
  51723. const size = range.count * byteOffsetFactor;
  51724. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  51725. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  51726. }
  51727. }
  51728. this.set( binding, map );
  51729. } else if ( binding.isSampledTexture ) {
  51730. const { textureGPU, glTextureType } = this.get( binding.texture );
  51731. map.textureGPU = textureGPU;
  51732. map.glTextureType = glTextureType;
  51733. this.set( binding, map );
  51734. }
  51735. }
  51736. }
  51737. /**
  51738. * Updates a buffer binding.
  51739. *
  51740. * @param {Buffer} binding - The buffer binding to update.
  51741. */
  51742. updateBinding( binding ) {
  51743. const gl = this.gl;
  51744. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  51745. const bindingData = this.get( binding );
  51746. const bufferGPU = bindingData.bufferGPU;
  51747. const array = binding.buffer;
  51748. const updateRanges = binding.updateRanges;
  51749. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  51750. if ( updateRanges.length === 0 ) {
  51751. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  51752. } else {
  51753. const isTyped = isTypedArray( array );
  51754. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  51755. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  51756. const range = updateRanges[ i ];
  51757. const dataOffset = range.start * byteOffsetFactor;
  51758. const size = range.count * byteOffsetFactor;
  51759. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  51760. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  51761. }
  51762. }
  51763. }
  51764. }
  51765. // attributes
  51766. /**
  51767. * Creates a uniform buffer.
  51768. *
  51769. * @param {Buffer} uniformBuffer - The uniform buffer.
  51770. */
  51771. createUniformBuffer( uniformBuffer ) {
  51772. const uniformBufferData = this.get( uniformBuffer );
  51773. if ( uniformBufferData.bufferGPU === undefined ) {
  51774. const gl = this.gl;
  51775. const array = uniformBuffer.buffer;
  51776. uniformBufferData.bufferGPU = gl.createBuffer();
  51777. gl.bindBuffer( gl.UNIFORM_BUFFER, uniformBufferData.bufferGPU );
  51778. gl.bufferData( gl.UNIFORM_BUFFER, array.byteLength, gl.DYNAMIC_DRAW );
  51779. }
  51780. }
  51781. /**
  51782. * Destroys the GPU data for the given uniform buffer.
  51783. *
  51784. * @param {Buffer} uniformBuffer - The uniform buffer.
  51785. */
  51786. destroyUniformBuffer( uniformBuffer ) {
  51787. const uniformBufferData = this.get( uniformBuffer );
  51788. this.gl.deleteBuffer( uniformBufferData.bufferGPU );
  51789. this.delete( uniformBuffer );
  51790. }
  51791. /**
  51792. * Creates the GPU buffer of an indexed shader attribute.
  51793. *
  51794. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  51795. */
  51796. createIndexAttribute( attribute ) {
  51797. const gl = this.gl;
  51798. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  51799. }
  51800. /**
  51801. * Creates the GPU buffer of a shader attribute.
  51802. *
  51803. * @param {BufferAttribute} attribute - The buffer attribute.
  51804. */
  51805. createAttribute( attribute ) {
  51806. if ( this.has( attribute ) ) return;
  51807. const gl = this.gl;
  51808. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  51809. }
  51810. /**
  51811. * Creates the GPU buffer of a storage attribute.
  51812. *
  51813. * @param {BufferAttribute} attribute - The buffer attribute.
  51814. */
  51815. createStorageAttribute( attribute ) {
  51816. if ( this.has( attribute ) ) return;
  51817. const gl = this.gl;
  51818. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  51819. }
  51820. /**
  51821. * Updates the GPU buffer of a shader attribute.
  51822. *
  51823. * @param {BufferAttribute} attribute - The buffer attribute to update.
  51824. */
  51825. updateAttribute( attribute ) {
  51826. this.attributeUtils.updateAttribute( attribute );
  51827. }
  51828. /**
  51829. * Destroys the GPU buffer of a shader attribute.
  51830. *
  51831. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  51832. */
  51833. destroyAttribute( attribute ) {
  51834. this.attributeUtils.destroyAttribute( attribute );
  51835. }
  51836. /**
  51837. * Checks if the given feature is supported by the backend.
  51838. *
  51839. * @param {string} name - The feature's name.
  51840. * @return {boolean} Whether the feature is supported or not.
  51841. */
  51842. hasFeature( name ) {
  51843. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  51844. const extensions = this.extensions;
  51845. for ( let i = 0; i < keysMatching.length; i ++ ) {
  51846. if ( extensions.has( keysMatching[ i ] ) ) return true;
  51847. }
  51848. return false;
  51849. }
  51850. /**
  51851. * Copies data of the given source texture to the given destination texture.
  51852. *
  51853. * @param {Texture} srcTexture - The source texture.
  51854. * @param {Texture} dstTexture - The destination texture.
  51855. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  51856. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  51857. * @param {number} [srcLevel=0] - The source mip level to copy from.
  51858. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  51859. */
  51860. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  51861. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  51862. }
  51863. /**
  51864. * Copies the current bound framebuffer to the given texture.
  51865. *
  51866. * @param {Texture} texture - The destination texture.
  51867. * @param {RenderContext} renderContext - The render context.
  51868. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  51869. */
  51870. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  51871. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  51872. }
  51873. /**
  51874. * Checks if the given compatibility is supported by the backend.
  51875. *
  51876. * @param {string} name - The compatibility name.
  51877. * @return {boolean} Whether the compatibility is supported or not.
  51878. */
  51879. hasCompatibility( name ) {
  51880. if ( name === Compatibility.TEXTURE_COMPARE ) return true;
  51881. return super.hasCompatibility( name );
  51882. }
  51883. /**
  51884. * Initializes the render target defined in the given render context.
  51885. *
  51886. * @param {RenderContext} renderContext - The render context.
  51887. */
  51888. initRenderTarget( renderContext ) {
  51889. const { gl, state } = this;
  51890. this._setFramebuffer( renderContext );
  51891. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  51892. }
  51893. /**
  51894. * Configures the active framebuffer from the given render context.
  51895. *
  51896. * @private
  51897. * @param {RenderContext} descriptor - The render context.
  51898. */
  51899. _setFramebuffer( descriptor ) {
  51900. const { gl, state } = this;
  51901. let currentFrameBuffer = null;
  51902. if ( descriptor.textures !== null ) {
  51903. const renderTarget = descriptor.renderTarget;
  51904. const renderTargetContextData = this.get( renderTarget );
  51905. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  51906. const isCube = renderTarget.isCubeRenderTarget === true;
  51907. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  51908. const isRenderTargetArray = renderTarget.depth > 1;
  51909. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  51910. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  51911. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  51912. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  51913. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  51914. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  51915. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  51916. const cacheKey = getCacheKey( descriptor );
  51917. let fb;
  51918. if ( isCube ) {
  51919. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  51920. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  51921. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  51922. fb = this._xrFramebuffer;
  51923. } else {
  51924. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  51925. fb = renderTargetContextData.framebuffers[ cacheKey ];
  51926. }
  51927. if ( fb === undefined ) {
  51928. fb = gl.createFramebuffer();
  51929. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  51930. const textures = descriptor.textures;
  51931. const depthInvalidationArray = [];
  51932. if ( isCube ) {
  51933. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  51934. const { textureGPU } = this.get( textures[ 0 ] );
  51935. const cubeFace = this.renderer._activeCubeFace;
  51936. const mipLevel = this.renderer._activeMipmapLevel;
  51937. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  51938. } else {
  51939. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  51940. for ( let i = 0; i < textures.length; i ++ ) {
  51941. const texture = textures[ i ];
  51942. const textureData = this.get( texture );
  51943. textureData.renderTarget = descriptor.renderTarget;
  51944. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  51945. const attachment = gl.COLOR_ATTACHMENT0 + i;
  51946. if ( renderTarget.multiview ) {
  51947. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  51948. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  51949. const layer = this.renderer._activeCubeFace;
  51950. const mipLevel = this.renderer._activeMipmapLevel;
  51951. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  51952. } else {
  51953. if ( useMultisampledRTT ) {
  51954. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  51955. } else {
  51956. const mipLevel = this.renderer._activeMipmapLevel;
  51957. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  51958. }
  51959. }
  51960. }
  51961. }
  51962. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  51963. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  51964. const renderbuffer = gl.createRenderbuffer();
  51965. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  51966. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  51967. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  51968. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  51969. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  51970. } else {
  51971. if ( descriptor.depthTexture !== null ) {
  51972. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  51973. const textureData = this.get( descriptor.depthTexture );
  51974. textureData.renderTarget = descriptor.renderTarget;
  51975. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  51976. if ( renderTarget.multiview ) {
  51977. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  51978. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  51979. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  51980. } else {
  51981. if ( descriptor.depthTexture.isArrayTexture ) {
  51982. const layer = this.renderer._activeCubeFace;
  51983. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  51984. } else if ( descriptor.depthTexture.isCubeTexture ) {
  51985. const cubeFace = this.renderer._activeCubeFace;
  51986. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureData.textureGPU, 0 );
  51987. } else {
  51988. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  51989. }
  51990. }
  51991. }
  51992. }
  51993. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  51994. } else {
  51995. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  51996. if ( isRenderCameraDepthArray ) {
  51997. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  51998. const layer = this.renderer._activeCubeFace;
  51999. const depthData = this.get( descriptor.depthTexture );
  52000. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  52001. gl.framebufferTextureLayer(
  52002. gl.FRAMEBUFFER,
  52003. depthStyle,
  52004. depthData.textureGPU,
  52005. 0,
  52006. layer
  52007. );
  52008. }
  52009. // rebind external XR textures
  52010. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  52011. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  52012. // rebind color
  52013. const textureData = this.get( descriptor.textures[ 0 ] );
  52014. if ( renderTarget.multiview ) {
  52015. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  52016. } else if ( useMultisampledRTT ) {
  52017. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  52018. } else {
  52019. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  52020. }
  52021. // rebind depth
  52022. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  52023. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  52024. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  52025. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  52026. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  52027. } else {
  52028. const textureData = this.get( descriptor.depthTexture );
  52029. if ( renderTarget.multiview ) {
  52030. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  52031. } else if ( useMultisampledRTT ) {
  52032. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  52033. } else {
  52034. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  52035. }
  52036. }
  52037. }
  52038. }
  52039. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  52040. if ( msaaFb === undefined ) {
  52041. const invalidationArray = [];
  52042. msaaFb = gl.createFramebuffer();
  52043. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  52044. const msaaRenderbuffers = [];
  52045. const textures = descriptor.textures;
  52046. for ( let i = 0; i < textures.length; i ++ ) {
  52047. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  52048. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  52049. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  52050. const texture = descriptor.textures[ i ];
  52051. const textureData = this.get( texture );
  52052. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  52053. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  52054. }
  52055. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  52056. renderTargetContextData.msaaFrameBuffer = msaaFb;
  52057. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  52058. if ( depthBuffer && depthRenderbuffer === undefined ) {
  52059. depthRenderbuffer = gl.createRenderbuffer();
  52060. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  52061. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  52062. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  52063. invalidationArray.push( depthStyle );
  52064. }
  52065. renderTargetContextData.invalidationArray = invalidationArray;
  52066. }
  52067. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  52068. } else {
  52069. currentFrameBuffer = fb;
  52070. }
  52071. state.drawBuffers( descriptor, fb );
  52072. }
  52073. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  52074. }
  52075. /**
  52076. * Computes the VAO key for the given index and attributes.
  52077. *
  52078. * @private
  52079. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  52080. * @return {string} The VAO key.
  52081. */
  52082. _getVaoKey( attributes ) {
  52083. let key = '';
  52084. for ( let i = 0; i < attributes.length; i ++ ) {
  52085. const attributeData = this.get( attributes[ i ] );
  52086. key += ':' + attributeData.id;
  52087. }
  52088. return key;
  52089. }
  52090. /**
  52091. * Creates a VAO from the index and attributes.
  52092. *
  52093. * @private
  52094. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  52095. * @return {Object} The VAO data.
  52096. */
  52097. _createVao( attributes ) {
  52098. const { gl } = this;
  52099. const vaoGPU = gl.createVertexArray();
  52100. gl.bindVertexArray( vaoGPU );
  52101. for ( let i = 0; i < attributes.length; i ++ ) {
  52102. const attribute = attributes[ i ];
  52103. const attributeData = this.get( attribute );
  52104. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  52105. gl.enableVertexAttribArray( i );
  52106. let stride, offset;
  52107. if ( attribute.isInterleavedBufferAttribute === true ) {
  52108. stride = attribute.data.stride * attributeData.bytesPerElement;
  52109. offset = attribute.offset * attributeData.bytesPerElement;
  52110. } else {
  52111. stride = 0;
  52112. offset = 0;
  52113. }
  52114. if ( attributeData.isInteger ) {
  52115. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  52116. } else {
  52117. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  52118. }
  52119. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  52120. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  52121. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  52122. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  52123. }
  52124. }
  52125. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  52126. return vaoGPU;
  52127. }
  52128. /**
  52129. * Creates a transform feedback from the given transform buffers.
  52130. *
  52131. * @private
  52132. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  52133. * @return {WebGLTransformFeedback} The transform feedback.
  52134. */
  52135. _getTransformFeedback( transformBuffers ) {
  52136. let key = '';
  52137. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  52138. key += ':' + transformBuffers[ i ].id;
  52139. }
  52140. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  52141. if ( transformFeedbackGPU !== undefined ) {
  52142. return transformFeedbackGPU;
  52143. }
  52144. const { gl } = this;
  52145. transformFeedbackGPU = gl.createTransformFeedback();
  52146. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  52147. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  52148. const attributeData = transformBuffers[ i ];
  52149. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  52150. }
  52151. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  52152. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  52153. return transformFeedbackGPU;
  52154. }
  52155. /**
  52156. * Setups the given bindings.
  52157. *
  52158. * @private
  52159. * @param {Array<BindGroup>} bindings - The bindings.
  52160. * @param {WebGLProgram} programGPU - The WebGL program.
  52161. */
  52162. _setupBindings( bindings, programGPU ) {
  52163. const gl = this.gl;
  52164. let uniformBuffers = 0;
  52165. let textures = 0;
  52166. for ( const bindGroup of bindings ) {
  52167. for ( const binding of bindGroup.bindings ) {
  52168. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  52169. const index = uniformBuffers ++;
  52170. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  52171. gl.uniformBlockBinding( programGPU, location, index );
  52172. } else if ( binding.isSampledTexture ) {
  52173. const index = textures ++;
  52174. const location = gl.getUniformLocation( programGPU, binding.name );
  52175. gl.uniform1i( location, index );
  52176. }
  52177. }
  52178. }
  52179. }
  52180. /**
  52181. * Binds the given uniforms.
  52182. *
  52183. * @private
  52184. * @param {Array<BindGroup>} bindings - The bindings.
  52185. */
  52186. _bindUniforms( bindings ) {
  52187. const { gl, state } = this;
  52188. let uniformBuffers = 0;
  52189. let textures = 0;
  52190. for ( const bindGroup of bindings ) {
  52191. for ( const binding of bindGroup.bindings ) {
  52192. const bindingData = this.get( binding );
  52193. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  52194. const index = uniformBuffers ++;
  52195. // TODO USE bindBufferRange to group multiple uniform buffers
  52196. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  52197. } else if ( binding.isSampledTexture ) {
  52198. const index = textures ++;
  52199. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  52200. }
  52201. }
  52202. }
  52203. }
  52204. /**
  52205. * The method ensures multisampled render targets are resolved.
  52206. *
  52207. * @private
  52208. * @param {RenderContext} renderContext - The render context.
  52209. */
  52210. _resolveRenderTarget( renderContext ) {
  52211. const { gl, state } = this;
  52212. const renderTarget = renderContext.renderTarget;
  52213. if ( renderContext.textures !== null && renderTarget ) {
  52214. const renderTargetContextData = this.get( renderTarget );
  52215. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  52216. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  52217. let mask = gl.COLOR_BUFFER_BIT;
  52218. if ( renderTarget.resolveDepthBuffer ) {
  52219. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  52220. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  52221. }
  52222. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  52223. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  52224. const textures = renderContext.textures;
  52225. const isMRT = textures.length > 1;
  52226. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  52227. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  52228. if ( isMRT ) {
  52229. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  52230. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  52231. for ( let i = 0; i < textures.length; i ++ ) {
  52232. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  52233. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  52234. }
  52235. }
  52236. for ( let i = 0; i < textures.length; i ++ ) {
  52237. if ( isMRT ) {
  52238. // configure attachment for resolve
  52239. const { textureGPU } = this.get( textures[ i ] );
  52240. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  52241. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  52242. }
  52243. if ( renderContext.scissor ) {
  52244. const { x, y, width, height } = renderContext.scissorValue;
  52245. const viewY = renderContext.height - height - y;
  52246. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  52247. } else {
  52248. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  52249. }
  52250. }
  52251. if ( isMRT ) {
  52252. // restore attachments
  52253. for ( let i = 0; i < textures.length; i ++ ) {
  52254. const { textureGPU } = this.get( textures[ i ] );
  52255. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  52256. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  52257. }
  52258. }
  52259. if ( this._supportsInvalidateFramebuffer === true ) {
  52260. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  52261. }
  52262. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  52263. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  52264. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  52265. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  52266. }
  52267. }
  52268. }
  52269. /**
  52270. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  52271. * should be used when MSAA is enabled.
  52272. *
  52273. * @private
  52274. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  52275. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  52276. */
  52277. _useMultisampledExtension( renderTarget ) {
  52278. if ( renderTarget.multiview === true ) {
  52279. return true;
  52280. }
  52281. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  52282. }
  52283. /**
  52284. * Frees internal resources.
  52285. */
  52286. dispose() {
  52287. if ( this.textureUtils !== null ) this.textureUtils.dispose();
  52288. const extension = this.extensions.get( 'WEBGL_lose_context' );
  52289. if ( extension ) extension.loseContext();
  52290. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  52291. }
  52292. }
  52293. const GPUPrimitiveTopology = {
  52294. PointList: 'point-list',
  52295. LineList: 'line-list',
  52296. LineStrip: 'line-strip',
  52297. TriangleList: 'triangle-list'};
  52298. const GPUShaderStage = ( typeof self !== 'undefined' && self.GPUShaderStage ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  52299. const GPUCompareFunction = {
  52300. Never: 'never',
  52301. Less: 'less',
  52302. Equal: 'equal',
  52303. LessEqual: 'less-equal',
  52304. Greater: 'greater',
  52305. NotEqual: 'not-equal',
  52306. GreaterEqual: 'greater-equal',
  52307. Always: 'always'
  52308. };
  52309. const GPUStoreOp = {
  52310. Store: 'store'};
  52311. const GPULoadOp = {
  52312. Load: 'load',
  52313. Clear: 'clear'
  52314. };
  52315. const GPUFrontFace = {
  52316. CCW: 'ccw',
  52317. CW: 'cw'
  52318. };
  52319. const GPUCullMode = {
  52320. None: 'none',
  52321. Back: 'back'
  52322. };
  52323. const GPUIndexFormat = {
  52324. Uint16: 'uint16',
  52325. Uint32: 'uint32'
  52326. };
  52327. const GPUTextureFormat = {
  52328. // 8-bit formats
  52329. R8Unorm: 'r8unorm',
  52330. R8Snorm: 'r8snorm',
  52331. R8Uint: 'r8uint',
  52332. R8Sint: 'r8sint',
  52333. // 16-bit formats
  52334. R16Uint: 'r16uint',
  52335. R16Sint: 'r16sint',
  52336. R16Float: 'r16float',
  52337. RG8Unorm: 'rg8unorm',
  52338. RG8Snorm: 'rg8snorm',
  52339. RG8Uint: 'rg8uint',
  52340. RG8Sint: 'rg8sint',
  52341. R16Unorm: 'r16unorm',
  52342. R16Snorm: 'r16snorm',
  52343. // 32-bit formats
  52344. R32Uint: 'r32uint',
  52345. R32Sint: 'r32sint',
  52346. R32Float: 'r32float',
  52347. RG16Uint: 'rg16uint',
  52348. RG16Sint: 'rg16sint',
  52349. RG16Float: 'rg16float',
  52350. RGBA8Unorm: 'rgba8unorm',
  52351. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  52352. RGBA8Snorm: 'rgba8snorm',
  52353. RGBA8Uint: 'rgba8uint',
  52354. RGBA8Sint: 'rgba8sint',
  52355. BGRA8Unorm: 'bgra8unorm',
  52356. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  52357. RG16Unorm: 'rg16unorm',
  52358. RG16Snorm: 'rg16snorm',
  52359. // Packed 32-bit formats
  52360. RGB9E5UFloat: 'rgb9e5ufloat',
  52361. RGB10A2Unorm: 'rgb10a2unorm',
  52362. RG11B10UFloat: 'rg11b10ufloat',
  52363. // 64-bit formats
  52364. RG32Uint: 'rg32uint',
  52365. RG32Sint: 'rg32sint',
  52366. RG32Float: 'rg32float',
  52367. RGBA16Uint: 'rgba16uint',
  52368. RGBA16Sint: 'rgba16sint',
  52369. RGBA16Float: 'rgba16float',
  52370. RGBA16Unorm: 'rgba16unorm',
  52371. RGBA16Snorm: 'rgba16snorm',
  52372. // 128-bit formats
  52373. RGBA32Uint: 'rgba32uint',
  52374. RGBA32Sint: 'rgba32sint',
  52375. RGBA32Float: 'rgba32float',
  52376. Depth16Unorm: 'depth16unorm',
  52377. Depth24Plus: 'depth24plus',
  52378. Depth24PlusStencil8: 'depth24plus-stencil8',
  52379. Depth32Float: 'depth32float',
  52380. // 'depth32float-stencil8' extension
  52381. Depth32FloatStencil8: 'depth32float-stencil8',
  52382. // BC compressed formats usable if 'texture-compression-bc' is both
  52383. // supported by the device/user agent and enabled in requestDevice.
  52384. BC1RGBAUnorm: 'bc1-rgba-unorm',
  52385. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  52386. BC2RGBAUnorm: 'bc2-rgba-unorm',
  52387. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  52388. BC3RGBAUnorm: 'bc3-rgba-unorm',
  52389. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  52390. BC4RUnorm: 'bc4-r-unorm',
  52391. BC4RSnorm: 'bc4-r-snorm',
  52392. BC5RGUnorm: 'bc5-rg-unorm',
  52393. BC5RGSnorm: 'bc5-rg-snorm',
  52394. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  52395. BC6HRGBFloat: 'bc6h-rgb-float',
  52396. BC7RGBAUnorm: 'bc7-rgba-unorm',
  52397. BC7RGBAUnormSRGB: 'bc7-rgba-unorm-srgb',
  52398. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  52399. // supported by the device/user agent and enabled in requestDevice.
  52400. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  52401. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  52402. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  52403. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  52404. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  52405. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  52406. EACR11Unorm: 'eac-r11unorm',
  52407. EACR11Snorm: 'eac-r11snorm',
  52408. EACRG11Unorm: 'eac-rg11unorm',
  52409. EACRG11Snorm: 'eac-rg11snorm',
  52410. // ASTC compressed formats usable if 'texture-compression-astc' is both
  52411. // supported by the device/user agent and enabled in requestDevice.
  52412. ASTC4x4Unorm: 'astc-4x4-unorm',
  52413. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  52414. ASTC5x4Unorm: 'astc-5x4-unorm',
  52415. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  52416. ASTC5x5Unorm: 'astc-5x5-unorm',
  52417. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  52418. ASTC6x5Unorm: 'astc-6x5-unorm',
  52419. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  52420. ASTC6x6Unorm: 'astc-6x6-unorm',
  52421. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  52422. ASTC8x5Unorm: 'astc-8x5-unorm',
  52423. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  52424. ASTC8x6Unorm: 'astc-8x6-unorm',
  52425. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  52426. ASTC8x8Unorm: 'astc-8x8-unorm',
  52427. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  52428. ASTC10x5Unorm: 'astc-10x5-unorm',
  52429. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  52430. ASTC10x6Unorm: 'astc-10x6-unorm',
  52431. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  52432. ASTC10x8Unorm: 'astc-10x8-unorm',
  52433. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  52434. ASTC10x10Unorm: 'astc-10x10-unorm',
  52435. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  52436. ASTC12x10Unorm: 'astc-12x10-unorm',
  52437. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  52438. ASTC12x12Unorm: 'astc-12x12-unorm',
  52439. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  52440. };
  52441. const GPUAddressMode = {
  52442. ClampToEdge: 'clamp-to-edge',
  52443. Repeat: 'repeat',
  52444. MirrorRepeat: 'mirror-repeat'
  52445. };
  52446. const GPUFilterMode = {
  52447. Linear: 'linear',
  52448. Nearest: 'nearest'
  52449. };
  52450. const GPUBlendFactor = {
  52451. Zero: 'zero',
  52452. One: 'one',
  52453. Src: 'src',
  52454. OneMinusSrc: 'one-minus-src',
  52455. SrcAlpha: 'src-alpha',
  52456. OneMinusSrcAlpha: 'one-minus-src-alpha',
  52457. Dst: 'dst',
  52458. OneMinusDst: 'one-minus-dst',
  52459. DstAlpha: 'dst-alpha',
  52460. OneMinusDstAlpha: 'one-minus-dst-alpha',
  52461. SrcAlphaSaturated: 'src-alpha-saturated',
  52462. Constant: 'constant',
  52463. OneMinusConstant: 'one-minus-constant'
  52464. };
  52465. const GPUBlendOperation = {
  52466. Add: 'add',
  52467. Subtract: 'subtract',
  52468. ReverseSubtract: 'reverse-subtract',
  52469. Min: 'min',
  52470. Max: 'max'
  52471. };
  52472. const GPUColorWriteFlags = {
  52473. None: 0,
  52474. All: 0xF
  52475. };
  52476. const GPUStencilOperation = {
  52477. Keep: 'keep',
  52478. Zero: 'zero',
  52479. Replace: 'replace',
  52480. Invert: 'invert',
  52481. IncrementClamp: 'increment-clamp',
  52482. DecrementClamp: 'decrement-clamp',
  52483. IncrementWrap: 'increment-wrap',
  52484. DecrementWrap: 'decrement-wrap'
  52485. };
  52486. const GPUBufferBindingType = {
  52487. Storage: 'storage',
  52488. ReadOnlyStorage: 'read-only-storage'
  52489. };
  52490. const GPUStorageTextureAccess = {
  52491. WriteOnly: 'write-only',
  52492. ReadOnly: 'read-only',
  52493. ReadWrite: 'read-write',
  52494. };
  52495. const GPUSamplerBindingType = {
  52496. NonFiltering: 'non-filtering',
  52497. Comparison: 'comparison'
  52498. };
  52499. const GPUTextureSampleType = {
  52500. Float: 'float',
  52501. UnfilterableFloat: 'unfilterable-float',
  52502. Depth: 'depth',
  52503. SInt: 'sint',
  52504. UInt: 'uint'
  52505. };
  52506. const GPUTextureDimension = {
  52507. TwoD: '2d',
  52508. ThreeD: '3d'
  52509. };
  52510. const GPUTextureViewDimension = {
  52511. TwoD: '2d',
  52512. TwoDArray: '2d-array',
  52513. Cube: 'cube',
  52514. ThreeD: '3d'
  52515. };
  52516. const GPUTextureAspect = {
  52517. All: 'all'};
  52518. const GPUInputStepMode = {
  52519. Vertex: 'vertex',
  52520. Instance: 'instance'
  52521. };
  52522. const GPUFeatureName = {
  52523. CoreFeaturesAndLimits: 'core-features-and-limits',
  52524. DepthClipControl: 'depth-clip-control',
  52525. Depth32FloatStencil8: 'depth32float-stencil8',
  52526. TextureCompressionBC: 'texture-compression-bc',
  52527. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  52528. TextureCompressionETC2: 'texture-compression-etc2',
  52529. TextureCompressionASTC: 'texture-compression-astc',
  52530. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  52531. TimestampQuery: 'timestamp-query',
  52532. IndirectFirstInstance: 'indirect-first-instance',
  52533. ShaderF16: 'shader-f16',
  52534. RG11B10UFloat: 'rg11b10ufloat-renderable',
  52535. BGRA8UNormStorage: 'bgra8unorm-storage',
  52536. Float32Filterable: 'float32-filterable',
  52537. Float32Blendable: 'float32-blendable',
  52538. ClipDistances: 'clip-distances',
  52539. DualSourceBlending: 'dual-source-blending',
  52540. Subgroups: 'subgroups',
  52541. TextureFormatsTier1: 'texture-formats-tier1',
  52542. TextureFormatsTier2: 'texture-formats-tier2'
  52543. };
  52544. const GPUFeatureMap = {
  52545. 'texture-compression-s3tc': 'texture-compression-bc',
  52546. 'texture-compression-etc1': 'texture-compression-etc2'
  52547. };
  52548. /**
  52549. * A special form of sampler binding type.
  52550. * It's texture value is managed by a node object.
  52551. *
  52552. * @private
  52553. * @augments Sampler
  52554. */
  52555. class NodeSampler extends Sampler {
  52556. /**
  52557. * Constructs a new node-based sampler.
  52558. *
  52559. * @param {string} name - The samplers's name.
  52560. * @param {TextureNode} textureNode - The texture node.
  52561. * @param {UniformGroupNode} groupNode - The uniform group node.
  52562. */
  52563. constructor( name, textureNode, groupNode ) {
  52564. super( name, textureNode ? textureNode.value : null );
  52565. /**
  52566. * The texture node.
  52567. *
  52568. * @type {TextureNode}
  52569. */
  52570. this.textureNode = textureNode;
  52571. /**
  52572. * The uniform group node.
  52573. *
  52574. * @type {UniformGroupNode}
  52575. */
  52576. this.groupNode = groupNode;
  52577. }
  52578. /**
  52579. * Updates the texture value of this sampler.
  52580. *
  52581. * @return {boolean} Whether the sampler needs an update or not.
  52582. */
  52583. update() {
  52584. const { textureNode } = this;
  52585. if ( this.texture !== textureNode.value ) {
  52586. this.texture = textureNode.value;
  52587. return true;
  52588. }
  52589. return super.update();
  52590. }
  52591. }
  52592. /**
  52593. * Represents a storage buffer binding type.
  52594. *
  52595. * @private
  52596. * @augments Buffer
  52597. */
  52598. class StorageBuffer extends Buffer {
  52599. /**
  52600. * Constructs a new uniform buffer.
  52601. *
  52602. * @param {string} name - The buffer's name.
  52603. * @param {BufferAttribute} attribute - The buffer attribute.
  52604. */
  52605. constructor( name, attribute ) {
  52606. super( name, attribute ? attribute.array : null );
  52607. /**
  52608. * This flag can be used for type testing.
  52609. *
  52610. * @private
  52611. * @type {BufferAttribute}
  52612. */
  52613. this._attribute = attribute;
  52614. /**
  52615. * This flag can be used for type testing.
  52616. *
  52617. * @type {boolean}
  52618. * @readonly
  52619. * @default true
  52620. */
  52621. this.isStorageBuffer = true;
  52622. }
  52623. /**
  52624. * The storage buffer attribute.
  52625. *
  52626. * @type {BufferAttribute}
  52627. */
  52628. get attribute() {
  52629. return this._attribute;
  52630. }
  52631. }
  52632. let _id = 0;
  52633. /**
  52634. * A special form of storage buffer binding type.
  52635. * It's buffer value is managed by a node object.
  52636. *
  52637. * @private
  52638. * @augments StorageBuffer
  52639. */
  52640. class NodeStorageBuffer extends StorageBuffer {
  52641. /**
  52642. * Constructs a new node-based storage buffer.
  52643. *
  52644. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  52645. * @param {UniformGroupNode} groupNode - The uniform group node.
  52646. */
  52647. constructor( nodeUniform, groupNode ) {
  52648. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  52649. /**
  52650. * The node uniform.
  52651. *
  52652. * @type {StorageBufferNode}
  52653. */
  52654. this.nodeUniform = nodeUniform;
  52655. /**
  52656. * The access type.
  52657. *
  52658. * @type {string}
  52659. */
  52660. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  52661. /**
  52662. * The uniform group node.
  52663. *
  52664. * @type {UniformGroupNode}
  52665. */
  52666. this.groupNode = groupNode;
  52667. }
  52668. /**
  52669. * The storage buffer attribute node.
  52670. *
  52671. * @type {StorageBufferAttribute}
  52672. */
  52673. get attribute() {
  52674. return this.nodeUniform.value;
  52675. }
  52676. /**
  52677. * The storage buffer.
  52678. *
  52679. * @type {Float32Array}
  52680. */
  52681. get buffer() {
  52682. return this.nodeUniform.value.array;
  52683. }
  52684. }
  52685. const _commandList = [ null ];
  52686. /**
  52687. * A WebGPU backend utility module with common helpers.
  52688. *
  52689. * @private
  52690. */
  52691. class WebGPUUtils {
  52692. /**
  52693. * Constructs a new utility object.
  52694. *
  52695. * @param {WebGPUBackend} backend - The WebGPU backend.
  52696. */
  52697. constructor( backend ) {
  52698. /**
  52699. * A reference to the WebGPU backend.
  52700. *
  52701. * @type {WebGPUBackend}
  52702. */
  52703. this.backend = backend;
  52704. /**
  52705. * Caches the preferred canvas format.
  52706. *
  52707. * @private
  52708. * @type {?string}
  52709. * @default null
  52710. */
  52711. this._preferredCanvasFormat = null;
  52712. }
  52713. /**
  52714. * Returns the depth/stencil GPU format for the given render context.
  52715. *
  52716. * @param {RenderContext} renderContext - The render context.
  52717. * @return {string} The depth/stencil GPU texture format.
  52718. */
  52719. getCurrentDepthStencilFormat( renderContext ) {
  52720. let format;
  52721. if ( renderContext.depth ) {
  52722. if ( renderContext.depthTexture !== null ) {
  52723. format = this.getTextureFormatGPU( renderContext.depthTexture );
  52724. } else if ( renderContext.stencil ) {
  52725. if ( this.backend.renderer.reversedDepthBuffer === true ) {
  52726. format = GPUTextureFormat.Depth32FloatStencil8;
  52727. } else {
  52728. format = GPUTextureFormat.Depth24PlusStencil8;
  52729. }
  52730. } else {
  52731. if ( this.backend.renderer.reversedDepthBuffer === true ) {
  52732. format = GPUTextureFormat.Depth32Float;
  52733. } else {
  52734. format = GPUTextureFormat.Depth24Plus;
  52735. }
  52736. }
  52737. }
  52738. return format;
  52739. }
  52740. /**
  52741. * Returns the GPU format for the given texture.
  52742. *
  52743. * @param {Texture} texture - The texture.
  52744. * @return {string} The GPU texture format.
  52745. */
  52746. getTextureFormatGPU( texture ) {
  52747. return this.backend.get( texture ).format;
  52748. }
  52749. /**
  52750. * Returns an object that defines the multi-sampling state of the given texture.
  52751. *
  52752. * @param {Texture} texture - The texture.
  52753. * @return {Object} The multi-sampling state.
  52754. */
  52755. getTextureSampleData( texture ) {
  52756. let samples;
  52757. if ( texture.isFramebufferTexture ) {
  52758. samples = 1;
  52759. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  52760. const renderer = this.backend.renderer;
  52761. const renderTarget = renderer.getRenderTarget();
  52762. samples = renderTarget ? renderTarget.samples : renderer.currentSamples;
  52763. } else if ( texture.renderTarget ) {
  52764. samples = texture.renderTarget.samples;
  52765. }
  52766. samples = this.getSampleCount( samples || 1 );
  52767. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  52768. const primarySamples = isMSAA ? 1 : samples;
  52769. return { samples, primarySamples, isMSAA };
  52770. }
  52771. /**
  52772. * Returns the default color attachment's GPU format of the current render context.
  52773. *
  52774. * @param {RenderContext} renderContext - The render context.
  52775. * @return {string} The GPU texture format of the default color attachment.
  52776. */
  52777. getCurrentColorFormat( renderContext ) {
  52778. let format;
  52779. if ( renderContext.textures !== null ) {
  52780. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  52781. } else {
  52782. format = this.getPreferredCanvasFormat(); // default context format
  52783. }
  52784. return format;
  52785. }
  52786. /**
  52787. * Returns the GPU formats of all color attachments of the current render context.
  52788. *
  52789. * @param {RenderContext} renderContext - The render context.
  52790. * @return {Array<string>} The GPU texture formats of all color attachments.
  52791. */
  52792. getCurrentColorFormats( renderContext ) {
  52793. if ( renderContext.textures !== null ) {
  52794. return renderContext.textures.map( t => this.getTextureFormatGPU( t ) );
  52795. } else {
  52796. return [ this.getPreferredCanvasFormat() ]; // default context format
  52797. }
  52798. }
  52799. /**
  52800. * Returns the output color space of the current render context.
  52801. *
  52802. * @param {RenderContext} renderContext - The render context.
  52803. * @return {string} The output color space.
  52804. */
  52805. getCurrentColorSpace( renderContext ) {
  52806. if ( renderContext.textures !== null ) {
  52807. return renderContext.textures[ 0 ].colorSpace;
  52808. }
  52809. return this.backend.renderer.outputColorSpace;
  52810. }
  52811. /**
  52812. * Returns GPU primitive topology for the given object and material.
  52813. *
  52814. * @param {Object3D} object - The 3D object.
  52815. * @param {Material} material - The material.
  52816. * @return {string} The GPU primitive topology.
  52817. */
  52818. getPrimitiveTopology( object, material ) {
  52819. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  52820. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  52821. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  52822. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  52823. }
  52824. /**
  52825. * Returns a modified sample count from the given sample count value.
  52826. *
  52827. * That is required since WebGPU only supports either 1 or 4.
  52828. *
  52829. * @param {number} sampleCount - The input sample count.
  52830. * @return {number} The (potentially updated) output sample count.
  52831. */
  52832. getSampleCount( sampleCount ) {
  52833. return sampleCount >= 4 ? 4 : 1;
  52834. }
  52835. /**
  52836. * Returns the sample count of the given render context.
  52837. *
  52838. * @param {RenderContext} renderContext - The render context.
  52839. * @return {number} The sample count.
  52840. */
  52841. getSampleCountRenderContext( renderContext ) {
  52842. if ( renderContext.textures !== null ) {
  52843. return this.getSampleCount( renderContext.sampleCount );
  52844. }
  52845. return this.getSampleCount( this.backend.renderer.currentSamples );
  52846. }
  52847. /**
  52848. * Returns the preferred canvas format.
  52849. *
  52850. * There is a separate method for this so it's possible to
  52851. * honor edge cases for specific devices.
  52852. *
  52853. * @return {string} The GPU texture format of the canvas.
  52854. */
  52855. getPreferredCanvasFormat() {
  52856. const parameters = this.backend.parameters;
  52857. const bufferType = parameters.outputType;
  52858. if ( bufferType === undefined ) {
  52859. if ( this._preferredCanvasFormat === null ) {
  52860. this._preferredCanvasFormat = navigator.gpu.getPreferredCanvasFormat();
  52861. }
  52862. return this._preferredCanvasFormat;
  52863. } else if ( bufferType === UnsignedByteType ) {
  52864. return GPUTextureFormat.BGRA8Unorm;
  52865. } else if ( bufferType === HalfFloatType ) {
  52866. return GPUTextureFormat.RGBA16Float;
  52867. } else {
  52868. throw new Error( 'THREE.WebGPUUtils: Unsupported output buffer type.' );
  52869. }
  52870. }
  52871. }
  52872. /**
  52873. * Submits a single GPU command to the device queue using a shared, module-scoped
  52874. * array to avoid per-call array allocations.
  52875. *
  52876. * @private
  52877. * @param {GPUDevice} device - The GPU device.
  52878. * @param {GPUCommandBuffer} command - The command buffer to submit.
  52879. */
  52880. function submit( device, command ) {
  52881. _commandList[ 0 ] = command;
  52882. device.queue.submit( _commandList );
  52883. _commandList[ 0 ] = null;
  52884. }
  52885. /**
  52886. * Reusable descriptor for `GPUDevice.createBindGroup()`.
  52887. *
  52888. * @private
  52889. */
  52890. class GPUBindGroupDescriptor {
  52891. constructor() {
  52892. /**
  52893. * The label of the bind group.
  52894. *
  52895. * @type {string}
  52896. */
  52897. this.label = '';
  52898. /**
  52899. * The bind group layout the bind group conforms to.
  52900. *
  52901. * @type {?GPUBindGroupLayout}
  52902. * @default null
  52903. */
  52904. this.layout = null;
  52905. /**
  52906. * The bind group entries.
  52907. *
  52908. * @type {Array<Object>}
  52909. */
  52910. this.entries = [];
  52911. }
  52912. /**
  52913. * Resets the descriptor to its default state. The internal `entries` array
  52914. * is emptied without releasing its backing storage.
  52915. */
  52916. reset() {
  52917. this.label = '';
  52918. this.layout = null;
  52919. this.entries.length = 0;
  52920. }
  52921. }
  52922. /**
  52923. * Reusable descriptor for `GPUDevice.createBuffer()`.
  52924. *
  52925. * @private
  52926. */
  52927. class GPUBufferDescriptor {
  52928. constructor() {
  52929. /**
  52930. * The label of the buffer.
  52931. *
  52932. * @type {string}
  52933. */
  52934. this.label = '';
  52935. /**
  52936. * The size of the buffer in bytes.
  52937. *
  52938. * @type {number}
  52939. * @default 0
  52940. */
  52941. this.size = 0;
  52942. /**
  52943. * The allowed usages for the buffer.
  52944. *
  52945. * @type {number}
  52946. * @default 0
  52947. */
  52948. this.usage = 0;
  52949. /**
  52950. * Whether the buffer is in the mapped state at creation.
  52951. *
  52952. * @type {boolean}
  52953. * @default false
  52954. */
  52955. this.mappedAtCreation = false;
  52956. }
  52957. /**
  52958. * Resets the descriptor to its default state.
  52959. */
  52960. reset() {
  52961. this.label = '';
  52962. this.size = 0;
  52963. this.usage = 0;
  52964. this.mappedAtCreation = false;
  52965. }
  52966. }
  52967. /**
  52968. * Reusable descriptor for `GPUDevice.createCommandEncoder()`.
  52969. *
  52970. * @private
  52971. */
  52972. class GPUCommandEncoderDescriptor {
  52973. constructor() {
  52974. /**
  52975. * The label of the command encoder.
  52976. *
  52977. * @type {string}
  52978. */
  52979. this.label = '';
  52980. }
  52981. /**
  52982. * Resets the descriptor to its default state.
  52983. */
  52984. reset() {
  52985. this.label = '';
  52986. }
  52987. }
  52988. /**
  52989. * Reusable descriptor for `GPUDevice.createRenderBundleEncoder()`.
  52990. *
  52991. * @private
  52992. */
  52993. class GPURenderBundleEncoderDescriptor {
  52994. constructor() {
  52995. /**
  52996. * The label of the render bundle encoder.
  52997. *
  52998. * @type {string}
  52999. */
  53000. this.label = '';
  53001. /**
  53002. * The formats of the color attachments the bundle is compatible with.
  53003. *
  53004. * @type {?Array<?string>}
  53005. * @default null
  53006. */
  53007. this.colorFormats = null;
  53008. /**
  53009. * The format of the depth/stencil attachment the bundle is compatible with.
  53010. *
  53011. * @type {string|undefined}
  53012. */
  53013. this.depthStencilFormat = undefined;
  53014. /**
  53015. * The number of samples per pixel the bundle is compatible with.
  53016. *
  53017. * @type {number}
  53018. * @default 1
  53019. */
  53020. this.sampleCount = 1;
  53021. /**
  53022. * Whether the depth attachment is read-only.
  53023. *
  53024. * @type {boolean}
  53025. * @default false
  53026. */
  53027. this.depthReadOnly = false;
  53028. /**
  53029. * Whether the stencil attachment is read-only.
  53030. *
  53031. * @type {boolean}
  53032. * @default false
  53033. */
  53034. this.stencilReadOnly = false;
  53035. }
  53036. /**
  53037. * Resets the descriptor to its default state.
  53038. */
  53039. reset() {
  53040. this.label = '';
  53041. this.colorFormats = null;
  53042. this.depthStencilFormat = undefined;
  53043. this.sampleCount = 1;
  53044. this.depthReadOnly = false;
  53045. this.stencilReadOnly = false;
  53046. }
  53047. }
  53048. /**
  53049. * Reusable descriptor for `GPURenderPassColorAttachment`, the type of each
  53050. * entry in `GPURenderPassDescriptor.colorAttachments`.
  53051. *
  53052. * @private
  53053. */
  53054. class GPURenderPassColorAttachment {
  53055. constructor() {
  53056. /**
  53057. * The texture view the pass renders into.
  53058. *
  53059. * @type {?GPUTextureView}
  53060. * @default null
  53061. */
  53062. this.view = null;
  53063. /**
  53064. * The depth slice the pass renders into.
  53065. *
  53066. * @type {number|undefined}
  53067. */
  53068. this.depthSlice = undefined;
  53069. /**
  53070. * The texture view that receives the resolved output of multisampled rendering.
  53071. *
  53072. * @type {?GPUTextureView|undefined}
  53073. */
  53074. this.resolveTarget = undefined;
  53075. /**
  53076. * The clear value used when `loadOp` is `'clear'`.
  53077. *
  53078. * @type {Object|undefined}
  53079. */
  53080. this.clearValue = undefined;
  53081. /**
  53082. * The load operation performed at the start of the pass.
  53083. *
  53084. * @type {string|undefined}
  53085. */
  53086. this.loadOp = undefined;
  53087. /**
  53088. * The store operation performed at the end of the pass.
  53089. *
  53090. * @type {string|undefined}
  53091. */
  53092. this.storeOp = undefined;
  53093. }
  53094. /**
  53095. * Resets the descriptor to its default state.
  53096. */
  53097. reset() {
  53098. this.view = null;
  53099. this.depthSlice = undefined;
  53100. this.resolveTarget = undefined;
  53101. this.clearValue = undefined;
  53102. this.loadOp = undefined;
  53103. this.storeOp = undefined;
  53104. }
  53105. }
  53106. /**
  53107. * Reusable descriptor for `GPUCommandEncoder.beginRenderPass()`.
  53108. *
  53109. * @private
  53110. */
  53111. class GPURenderPassDescriptor {
  53112. constructor() {
  53113. /**
  53114. * The label of the render pass.
  53115. *
  53116. * @type {string}
  53117. */
  53118. this.label = '';
  53119. /**
  53120. * The color attachments of the render pass.
  53121. *
  53122. * @type {Array<?Object>}
  53123. */
  53124. this.colorAttachments = [];
  53125. /**
  53126. * The depth-stencil attachment of the render pass.
  53127. *
  53128. * @type {Object|undefined}
  53129. */
  53130. this.depthStencilAttachment = undefined;
  53131. /**
  53132. * The query set used for occlusion queries during the pass.
  53133. *
  53134. * @type {?GPUQuerySet|undefined}
  53135. */
  53136. this.occlusionQuerySet = undefined;
  53137. /**
  53138. * Defines which timestamp values are written and where.
  53139. *
  53140. * @type {Object|undefined}
  53141. */
  53142. this.timestampWrites = undefined;
  53143. /**
  53144. * The maximum number of draw calls that can be issued during the pass.
  53145. *
  53146. * @type {number}
  53147. * @default 50000000
  53148. */
  53149. this.maxDrawCount = 50000000;
  53150. }
  53151. /**
  53152. * Resets the descriptor to its default state. The internal `colorAttachments`
  53153. * array is emptied without releasing its backing storage.
  53154. */
  53155. reset() {
  53156. this.label = '';
  53157. this.colorAttachments.length = 0;
  53158. this.depthStencilAttachment = undefined;
  53159. this.occlusionQuerySet = undefined;
  53160. this.timestampWrites = undefined;
  53161. this.maxDrawCount = 50000000;
  53162. }
  53163. }
  53164. /**
  53165. * Reusable descriptor for `GPUDevice.createRenderPipeline()` and
  53166. * `createRenderPipelineAsync()`.
  53167. *
  53168. * @private
  53169. */
  53170. class GPURenderPipelineDescriptor {
  53171. constructor() {
  53172. /**
  53173. * The label of the render pipeline.
  53174. *
  53175. * @type {string}
  53176. */
  53177. this.label = '';
  53178. /**
  53179. * The pipeline layout the pipeline conforms to, or `'auto'`.
  53180. *
  53181. * @type {?GPUPipelineLayout|string}
  53182. * @default null
  53183. */
  53184. this.layout = null;
  53185. /**
  53186. * The programmable vertex stage.
  53187. *
  53188. * @type {?Object}
  53189. * @default null
  53190. */
  53191. this.vertex = null;
  53192. /**
  53193. * The primitive-assembly state.
  53194. *
  53195. * @type {Object}
  53196. */
  53197. this.primitive = {};
  53198. /**
  53199. * The depth/stencil state, omitted when the pipeline has no depth or stencil aspect.
  53200. *
  53201. * @type {Object|undefined}
  53202. */
  53203. this.depthStencil = undefined;
  53204. /**
  53205. * The multisample state.
  53206. *
  53207. * @type {GPUMultisampleState}
  53208. */
  53209. this.multisample = new GPUMultisampleState();
  53210. /**
  53211. * The programmable fragment stage. Omitted for vertex-only pipelines.
  53212. *
  53213. * @type {?Object}
  53214. * @default null
  53215. */
  53216. this.fragment = null;
  53217. }
  53218. /**
  53219. * Resets the descriptor to its default state.
  53220. */
  53221. reset() {
  53222. this.label = '';
  53223. this.layout = null;
  53224. this.vertex = null;
  53225. this.primitive = {};
  53226. this.depthStencil = undefined;
  53227. this.multisample.reset();
  53228. this.fragment = null;
  53229. }
  53230. }
  53231. /**
  53232. * Reusable nested state for `GPURenderPipelineDescriptor.multisample`.
  53233. *
  53234. * @private
  53235. */
  53236. class GPUMultisampleState {
  53237. constructor() {
  53238. /**
  53239. * The number of samples per pixel.
  53240. *
  53241. * @type {number}
  53242. * @default 1
  53243. */
  53244. this.count = 1;
  53245. /**
  53246. * A bitmask determining which samples are written to.
  53247. *
  53248. * @type {number}
  53249. * @default 0xFFFFFFFF
  53250. */
  53251. this.mask = 0xFFFFFFFF;
  53252. /**
  53253. * Whether a fragment's alpha channel is used to generate a sample coverage mask.
  53254. *
  53255. * @type {boolean}
  53256. * @default false
  53257. */
  53258. this.alphaToCoverageEnabled = false;
  53259. }
  53260. /**
  53261. * Resets the state to its default values.
  53262. */
  53263. reset() {
  53264. this.count = 1;
  53265. this.mask = 0xFFFFFFFF;
  53266. this.alphaToCoverageEnabled = false;
  53267. }
  53268. }
  53269. /**
  53270. * Reusable descriptor for `GPUDevice.createShaderModule()`.
  53271. *
  53272. * @private
  53273. */
  53274. class GPUShaderModuleDescriptor {
  53275. constructor() {
  53276. /**
  53277. * The label of the shader module.
  53278. *
  53279. * @type {string}
  53280. */
  53281. this.label = '';
  53282. /**
  53283. * The WGSL source code of the shader module.
  53284. *
  53285. * @type {string}
  53286. */
  53287. this.code = '';
  53288. /**
  53289. * Compilation hints that may help the implementation produce optimized code.
  53290. *
  53291. * @type {Array<Object>}
  53292. */
  53293. this.compilationHints = [];
  53294. }
  53295. /**
  53296. * Resets the descriptor to its default state.
  53297. */
  53298. reset() {
  53299. this.label = '';
  53300. this.code = '';
  53301. this.compilationHints.length = 0;
  53302. }
  53303. }
  53304. /**
  53305. * Reusable descriptor for `GPUDevice.createTexture()`.
  53306. *
  53307. * @private
  53308. */
  53309. class GPUTextureDescriptor {
  53310. constructor() {
  53311. /**
  53312. * The label of the texture.
  53313. *
  53314. * @type {string}
  53315. */
  53316. this.label = '';
  53317. /**
  53318. * The size of the texture.
  53319. *
  53320. * @type {{width: number, height: number, depthOrArrayLayers: number}}
  53321. */
  53322. this.size = { width: 0, height: 1, depthOrArrayLayers: 1 };
  53323. /**
  53324. * The number of mip levels the texture will contain.
  53325. *
  53326. * @type {number}
  53327. * @default 1
  53328. */
  53329. this.mipLevelCount = 1;
  53330. /**
  53331. * The sample count of the texture.
  53332. *
  53333. * @type {number}
  53334. * @default 1
  53335. */
  53336. this.sampleCount = 1;
  53337. /**
  53338. * The dimension of the set of texel coordinates.
  53339. *
  53340. * @type {string}
  53341. * @default '2d'
  53342. */
  53343. this.dimension = '2d';
  53344. /**
  53345. * The format of the texture.
  53346. *
  53347. * @type {string|undefined}
  53348. */
  53349. this.format = undefined;
  53350. /**
  53351. * The allowed usages for the texture.
  53352. *
  53353. * @type {number|undefined}
  53354. */
  53355. this.usage = undefined;
  53356. /**
  53357. * The formats that views of this texture may use.
  53358. *
  53359. * @type {Array<string>}
  53360. */
  53361. this.viewFormats = [];
  53362. /**
  53363. * The view dimension to use when binding the texture (compatibility mode).
  53364. *
  53365. * @type {string|undefined}
  53366. */
  53367. this.textureBindingViewDimension = undefined;
  53368. }
  53369. /**
  53370. * Resets the descriptor to its default state.
  53371. */
  53372. reset() {
  53373. this.label = '';
  53374. this.size.width = 0;
  53375. this.size.height = 1;
  53376. this.size.depthOrArrayLayers = 1;
  53377. this.mipLevelCount = 1;
  53378. this.sampleCount = 1;
  53379. this.dimension = '2d';
  53380. this.format = undefined;
  53381. this.usage = undefined;
  53382. this.viewFormats.length = 0;
  53383. this.textureBindingViewDimension = undefined;
  53384. }
  53385. }
  53386. /**
  53387. * Reusable descriptor for `GPUTexture.createView()`.
  53388. *
  53389. * @private
  53390. */
  53391. class GPUTextureViewDescriptor {
  53392. constructor() {
  53393. /**
  53394. * The label of the texture view.
  53395. *
  53396. * @type {string}
  53397. */
  53398. this.label = '';
  53399. /**
  53400. * The format of the texture view.
  53401. *
  53402. * @type {string|undefined}
  53403. */
  53404. this.format = undefined;
  53405. /**
  53406. * The dimension of the texture view.
  53407. *
  53408. * @type {string|undefined}
  53409. */
  53410. this.dimension = undefined;
  53411. /**
  53412. * The allowed usages for the texture view.
  53413. *
  53414. * @type {number}
  53415. * @default 0
  53416. */
  53417. this.usage = 0;
  53418. /**
  53419. * Which aspect of the texture is referenced.
  53420. *
  53421. * @type {string}
  53422. * @default 'all'
  53423. */
  53424. this.aspect = 'all';
  53425. /**
  53426. * The first mip level accessible to the texture view.
  53427. *
  53428. * @type {number}
  53429. * @default 0
  53430. */
  53431. this.baseMipLevel = 0;
  53432. /**
  53433. * The number of mip levels accessible to the texture view.
  53434. *
  53435. * @type {number|undefined}
  53436. */
  53437. this.mipLevelCount = undefined;
  53438. /**
  53439. * The first array layer accessible to the texture view.
  53440. *
  53441. * @type {number}
  53442. * @default 0
  53443. */
  53444. this.baseArrayLayer = 0;
  53445. /**
  53446. * The number of array layers accessible to the texture view.
  53447. *
  53448. * @type {number|undefined}
  53449. */
  53450. this.arrayLayerCount = undefined;
  53451. /**
  53452. * The component swizzle to apply when sampling the texture view.
  53453. * Requires the `'texture-component-swizzle'` feature; ignored otherwise.
  53454. *
  53455. * @type {string}
  53456. * @default 'rgba'
  53457. */
  53458. this.swizzle = 'rgba';
  53459. }
  53460. /**
  53461. * Resets the descriptor to its default state.
  53462. */
  53463. reset() {
  53464. this.label = '';
  53465. this.format = undefined;
  53466. this.dimension = undefined;
  53467. this.usage = 0;
  53468. this.aspect = 'all';
  53469. this.baseMipLevel = 0;
  53470. this.mipLevelCount = undefined;
  53471. this.baseArrayLayer = 0;
  53472. this.arrayLayerCount = undefined;
  53473. this.swizzle = 'rgba';
  53474. }
  53475. }
  53476. const _bindGroupDescriptor$1 = new GPUBindGroupDescriptor();
  53477. const _bufferDescriptor$5 = new GPUBufferDescriptor();
  53478. const _commandEncoderDescriptor$4 = new GPUCommandEncoderDescriptor();
  53479. const _renderBundleEncoderDescriptor$1 = new GPURenderBundleEncoderDescriptor();
  53480. const _renderPassDescriptor = new GPURenderPassDescriptor();
  53481. const _renderPipelineDescriptor$1 = new GPURenderPipelineDescriptor();
  53482. const _colorAttachment = new GPURenderPassColorAttachment();
  53483. const _shaderModuleDescriptor$1 = new GPUShaderModuleDescriptor();
  53484. const _textureDescriptor$1 = new GPUTextureDescriptor();
  53485. const _viewDescriptor$2 = new GPUTextureViewDescriptor();
  53486. /**
  53487. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  53488. *
  53489. * @private
  53490. */
  53491. class WebGPUTexturePassUtils extends DataMap {
  53492. /**
  53493. * Constructs a new utility object.
  53494. *
  53495. * @param {GPUDevice} device - The WebGPU device.
  53496. */
  53497. constructor( device ) {
  53498. super();
  53499. /**
  53500. * The WebGPU device.
  53501. *
  53502. * @type {GPUDevice}
  53503. */
  53504. this.device = device;
  53505. const mipmapSource = `
  53506. struct VarysStruct {
  53507. @builtin( position ) Position: vec4f,
  53508. @location( 0 ) vTex : vec2f,
  53509. @location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,
  53510. };
  53511. @group( 0 ) @binding ( 2 )
  53512. var<uniform> flipY: u32;
  53513. @vertex
  53514. fn mainVS(
  53515. @builtin( vertex_index ) vertexIndex : u32,
  53516. @builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {
  53517. var Varys : VarysStruct;
  53518. var pos = array(
  53519. vec2f( -1, -1 ),
  53520. vec2f( -1, 3 ),
  53521. vec2f( 3, -1 ),
  53522. );
  53523. let p = pos[ vertexIndex ];
  53524. let mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );
  53525. Varys.vTex = p * mult + vec2f( 0.5 );
  53526. Varys.Position = vec4f( p, 0, 1 );
  53527. Varys.vBaseArrayLayer = instanceIndex;
  53528. return Varys;
  53529. }
  53530. @group( 0 ) @binding( 0 )
  53531. var imgSampler : sampler;
  53532. @group( 0 ) @binding( 1 )
  53533. var img2d : texture_2d<f32>;
  53534. @fragment
  53535. fn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
  53536. return textureSample( img2d, imgSampler, Varys.vTex );
  53537. }
  53538. @group( 0 ) @binding( 1 )
  53539. var img2dArray : texture_2d_array<f32>;
  53540. @fragment
  53541. fn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
  53542. return textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );
  53543. }
  53544. const faceMat = array(
  53545. mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x
  53546. mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x
  53547. mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y
  53548. mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y
  53549. mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z
  53550. mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z
  53551. );
  53552. @group( 0 ) @binding( 1 )
  53553. var imgCube : texture_cube<f32>;
  53554. @fragment
  53555. fn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
  53556. return textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );
  53557. }
  53558. `;
  53559. /**
  53560. * The mipmap GPU sampler.
  53561. *
  53562. * @type {GPUSampler}
  53563. */
  53564. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  53565. /**
  53566. * The flipY GPU sampler.
  53567. *
  53568. * @type {GPUSampler}
  53569. */
  53570. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  53571. /**
  53572. * flip uniform buffer
  53573. * @type {GPUBuffer}
  53574. */
  53575. _bufferDescriptor$5.size = 4;
  53576. _bufferDescriptor$5.usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  53577. this.flipUniformBuffer = device.createBuffer( _bufferDescriptor$5 );
  53578. _bufferDescriptor$5.reset();
  53579. device.queue.writeBuffer( this.flipUniformBuffer, 0, new Uint32Array( [ 1 ] ) );
  53580. /**
  53581. * no flip uniform buffer
  53582. * @type {GPUBuffer}
  53583. */
  53584. _bufferDescriptor$5.size = 4;
  53585. _bufferDescriptor$5.usage = GPUBufferUsage.UNIFORM;
  53586. this.noFlipUniformBuffer = device.createBuffer( _bufferDescriptor$5 );
  53587. _bufferDescriptor$5.reset();
  53588. /**
  53589. * A cache for GPU render pipelines used for copy/transfer passes.
  53590. * Every texture format and textureBindingViewDimension combo requires a unique pipeline.
  53591. *
  53592. * @type {Object<string,GPURenderPipeline>}
  53593. */
  53594. this.transferPipelines = {};
  53595. /**
  53596. * The mipmap shader module.
  53597. *
  53598. * @type {GPUShaderModule}
  53599. */
  53600. _shaderModuleDescriptor$1.label = 'mipmap';
  53601. _shaderModuleDescriptor$1.code = mipmapSource;
  53602. this.mipmapShaderModule = device.createShaderModule( _shaderModuleDescriptor$1 );
  53603. _shaderModuleDescriptor$1.reset();
  53604. }
  53605. /**
  53606. * Returns a render pipeline for the internal copy render pass. The pass
  53607. * requires a unique render pipeline for each texture format.
  53608. *
  53609. * @param {string} format - The GPU texture format
  53610. * @param {string?} textureBindingViewDimension - The GPU texture binding view dimension
  53611. * @return {GPURenderPipeline} The GPU render pipeline.
  53612. */
  53613. getTransferPipeline( format, textureBindingViewDimension ) {
  53614. textureBindingViewDimension = textureBindingViewDimension || '2d-array';
  53615. const key = `${ format }-${ textureBindingViewDimension }`;
  53616. let pipeline = this.transferPipelines[ key ];
  53617. if ( pipeline === undefined ) {
  53618. _renderPipelineDescriptor$1.label = `mipmap-${ format }-${ textureBindingViewDimension }`;
  53619. _renderPipelineDescriptor$1.vertex = { module: this.mipmapShaderModule };
  53620. _renderPipelineDescriptor$1.fragment = {
  53621. module: this.mipmapShaderModule,
  53622. entryPoint: `main_${ textureBindingViewDimension.replace( '-', '_' ) }`,
  53623. targets: [ { format } ]
  53624. };
  53625. _renderPipelineDescriptor$1.layout = 'auto';
  53626. pipeline = this.device.createRenderPipeline( _renderPipelineDescriptor$1 );
  53627. _renderPipelineDescriptor$1.reset();
  53628. this.transferPipelines[ key ] = pipeline;
  53629. }
  53630. return pipeline;
  53631. }
  53632. /**
  53633. * Flip the contents of the given GPU texture along its vertical axis.
  53634. *
  53635. * @param {GPUTexture} textureGPU - The GPU texture object.
  53636. * @param {Object} textureGPUDescriptor - The texture descriptor.
  53637. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  53638. */
  53639. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  53640. const format = textureGPUDescriptor.format;
  53641. const { width, height } = textureGPUDescriptor.size;
  53642. _textureDescriptor$1.size.width = width;
  53643. _textureDescriptor$1.size.height = height;
  53644. _textureDescriptor$1.format = format;
  53645. _textureDescriptor$1.usage = GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING;
  53646. const tempTexture = this.device.createTexture( _textureDescriptor$1 );
  53647. _textureDescriptor$1.reset();
  53648. const copyTransferPipeline = this.getTransferPipeline( format, textureGPU.textureBindingViewDimension );
  53649. const flipTransferPipeline = this.getTransferPipeline( format, tempTexture.textureBindingViewDimension );
  53650. const commandEncoder = this.device.createCommandEncoder( _commandEncoderDescriptor$4 );
  53651. const pass = ( pipeline, sourceTexture, sourceArrayLayer, destinationTexture, destinationArrayLayer, flipY ) => {
  53652. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  53653. _viewDescriptor$2.dimension = sourceTexture.textureBindingViewDimension || '2d-array';
  53654. _viewDescriptor$2.mipLevelCount = 1;
  53655. const sourceView = sourceTexture.createView( _viewDescriptor$2 );
  53656. _viewDescriptor$2.reset();
  53657. _bindGroupDescriptor$1.layout = bindGroupLayout;
  53658. _bindGroupDescriptor$1.entries.push( {
  53659. binding: 0,
  53660. resource: this.flipYSampler
  53661. }, {
  53662. binding: 1,
  53663. resource: sourceView,
  53664. }, {
  53665. binding: 2,
  53666. resource: { buffer: flipY ? this.flipUniformBuffer : this.noFlipUniformBuffer }
  53667. } );
  53668. const bindGroup = this.device.createBindGroup( _bindGroupDescriptor$1 );
  53669. _bindGroupDescriptor$1.reset();
  53670. _viewDescriptor$2.dimension = '2d';
  53671. _viewDescriptor$2.mipLevelCount = 1;
  53672. _viewDescriptor$2.baseArrayLayer = destinationArrayLayer;
  53673. _viewDescriptor$2.arrayLayerCount = 1;
  53674. const destinationView = destinationTexture.createView( _viewDescriptor$2 );
  53675. _viewDescriptor$2.reset();
  53676. _colorAttachment.view = destinationView;
  53677. _colorAttachment.loadOp = GPULoadOp.Clear;
  53678. _colorAttachment.storeOp = GPUStoreOp.Store;
  53679. _renderPassDescriptor.colorAttachments.push( _colorAttachment );
  53680. const passEncoder = commandEncoder.beginRenderPass( _renderPassDescriptor );
  53681. _renderPassDescriptor.reset();
  53682. _colorAttachment.reset();
  53683. passEncoder.setPipeline( pipeline );
  53684. passEncoder.setBindGroup( 0, bindGroup );
  53685. passEncoder.draw( 3, 1, 0, sourceArrayLayer );
  53686. passEncoder.end();
  53687. };
  53688. pass( copyTransferPipeline, textureGPU, baseArrayLayer, tempTexture, 0, false );
  53689. pass( flipTransferPipeline, tempTexture, 0, textureGPU, baseArrayLayer, true );
  53690. submit( this.device, commandEncoder.finish() );
  53691. tempTexture.destroy();
  53692. }
  53693. /**
  53694. * Generates mipmaps for the given GPU texture.
  53695. *
  53696. * @param {GPUTexture} textureGPU - The GPU texture object.
  53697. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  53698. */
  53699. generateMipmaps( textureGPU, encoder = null ) {
  53700. const textureData = this.get( textureGPU );
  53701. const passes = textureData.layers || this._mipmapCreateBundles( textureGPU );
  53702. let commandEncoder = encoder;
  53703. if ( commandEncoder === null ) {
  53704. _commandEncoderDescriptor$4.label = 'mipmapEncoder';
  53705. commandEncoder = this.device.createCommandEncoder( _commandEncoderDescriptor$4 );
  53706. _commandEncoderDescriptor$4.reset();
  53707. }
  53708. this._mipmapRunBundles( commandEncoder, passes );
  53709. if ( encoder === null ) submit( this.device, commandEncoder.finish() );
  53710. textureData.layers = passes;
  53711. }
  53712. /**
  53713. * Since multiple copy render passes are required to generate mipmaps, the passes
  53714. * are managed as render bundles to improve performance.
  53715. *
  53716. * @param {GPUTexture} textureGPU - The GPU texture object.
  53717. * @return {Array<Object>} An array of render bundles.
  53718. */
  53719. _mipmapCreateBundles( textureGPU ) {
  53720. const textureBindingViewDimension = textureGPU.textureBindingViewDimension || '2d-array';
  53721. const pipeline = this.getTransferPipeline( textureGPU.format, textureBindingViewDimension );
  53722. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  53723. const passes = [];
  53724. for ( let baseMipLevel = 1; baseMipLevel < textureGPU.mipLevelCount; baseMipLevel ++ ) {
  53725. for ( let baseArrayLayer = 0; baseArrayLayer < textureGPU.depthOrArrayLayers; baseArrayLayer ++ ) {
  53726. _viewDescriptor$2.dimension = textureBindingViewDimension;
  53727. _viewDescriptor$2.baseMipLevel = baseMipLevel - 1;
  53728. _viewDescriptor$2.mipLevelCount = 1;
  53729. const sourceView = textureGPU.createView( _viewDescriptor$2 );
  53730. _viewDescriptor$2.reset();
  53731. _bindGroupDescriptor$1.layout = bindGroupLayout;
  53732. _bindGroupDescriptor$1.entries.push( {
  53733. binding: 0,
  53734. resource: this.mipmapSampler
  53735. }, {
  53736. binding: 1,
  53737. resource: sourceView,
  53738. }, {
  53739. binding: 2,
  53740. resource: { buffer: this.noFlipUniformBuffer }
  53741. } );
  53742. const bindGroup = this.device.createBindGroup( _bindGroupDescriptor$1 );
  53743. _bindGroupDescriptor$1.reset();
  53744. _viewDescriptor$2.dimension = '2d';
  53745. _viewDescriptor$2.baseMipLevel = baseMipLevel;
  53746. _viewDescriptor$2.mipLevelCount = 1;
  53747. _viewDescriptor$2.baseArrayLayer = baseArrayLayer;
  53748. _viewDescriptor$2.arrayLayerCount = 1;
  53749. const destinationView = textureGPU.createView( _viewDescriptor$2 );
  53750. _viewDescriptor$2.reset();
  53751. const passColorAttachment = new GPURenderPassColorAttachment();
  53752. passColorAttachment.view = destinationView;
  53753. passColorAttachment.loadOp = GPULoadOp.Clear;
  53754. passColorAttachment.storeOp = GPUStoreOp.Store;
  53755. const passDescriptor = new GPURenderPassDescriptor();
  53756. passDescriptor.colorAttachments.push( passColorAttachment );
  53757. _renderBundleEncoderDescriptor$1.colorFormats = [ textureGPU.format ];
  53758. const passEncoder = this.device.createRenderBundleEncoder( _renderBundleEncoderDescriptor$1 );
  53759. _renderBundleEncoderDescriptor$1.reset();
  53760. passEncoder.setPipeline( pipeline );
  53761. passEncoder.setBindGroup( 0, bindGroup );
  53762. passEncoder.draw( 3, 1, 0, baseArrayLayer );
  53763. passes.push( {
  53764. renderBundles: [ passEncoder.finish() ],
  53765. passDescriptor
  53766. } );
  53767. }
  53768. }
  53769. return passes;
  53770. }
  53771. /**
  53772. * Executes the render bundles.
  53773. *
  53774. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  53775. * @param {Array<Object>} passes - An array of render bundles.
  53776. */
  53777. _mipmapRunBundles( commandEncoder, passes ) {
  53778. const levels = passes.length;
  53779. for ( let i = 0; i < levels; i ++ ) {
  53780. const pass = passes[ i ];
  53781. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  53782. passEncoder.executeBundles( pass.renderBundles );
  53783. passEncoder.end();
  53784. }
  53785. }
  53786. }
  53787. /**
  53788. * Reusable descriptor for `GPUDevice.createSampler()`.
  53789. *
  53790. * @private
  53791. */
  53792. class GPUSamplerDescriptor {
  53793. constructor() {
  53794. /**
  53795. * The label of the sampler.
  53796. *
  53797. * @type {string}
  53798. */
  53799. this.label = '';
  53800. /**
  53801. * The address mode for the sampler's U coordinate.
  53802. *
  53803. * @type {string}
  53804. * @default 'clamp-to-edge'
  53805. */
  53806. this.addressModeU = 'clamp-to-edge';
  53807. /**
  53808. * The address mode for the sampler's V coordinate.
  53809. *
  53810. * @type {string}
  53811. * @default 'clamp-to-edge'
  53812. */
  53813. this.addressModeV = 'clamp-to-edge';
  53814. /**
  53815. * The address mode for the sampler's W coordinate.
  53816. *
  53817. * @type {string}
  53818. * @default 'clamp-to-edge'
  53819. */
  53820. this.addressModeW = 'clamp-to-edge';
  53821. /**
  53822. * The magnification filter mode.
  53823. *
  53824. * @type {string}
  53825. * @default 'nearest'
  53826. */
  53827. this.magFilter = 'nearest';
  53828. /**
  53829. * The minification filter mode.
  53830. *
  53831. * @type {string}
  53832. * @default 'nearest'
  53833. */
  53834. this.minFilter = 'nearest';
  53835. /**
  53836. * The mipmap filter mode.
  53837. *
  53838. * @type {string}
  53839. * @default 'nearest'
  53840. */
  53841. this.mipmapFilter = 'nearest';
  53842. /**
  53843. * The minimum level of detail used to sample.
  53844. *
  53845. * @type {number}
  53846. * @default 0
  53847. */
  53848. this.lodMinClamp = 0;
  53849. /**
  53850. * The maximum level of detail used to sample.
  53851. *
  53852. * @type {number}
  53853. * @default 32
  53854. */
  53855. this.lodMaxClamp = 32;
  53856. /**
  53857. * The compare function used by the sampler.
  53858. *
  53859. * @type {string|undefined}
  53860. */
  53861. this.compare = undefined;
  53862. /**
  53863. * The maximum allowed anisotropic filtering.
  53864. *
  53865. * @type {number}
  53866. * @default 1
  53867. */
  53868. this.maxAnisotropy = 1;
  53869. }
  53870. /**
  53871. * Resets the descriptor to its default state.
  53872. */
  53873. reset() {
  53874. this.label = '';
  53875. this.addressModeU = 'clamp-to-edge';
  53876. this.addressModeV = 'clamp-to-edge';
  53877. this.addressModeW = 'clamp-to-edge';
  53878. this.magFilter = 'nearest';
  53879. this.minFilter = 'nearest';
  53880. this.mipmapFilter = 'nearest';
  53881. this.lodMinClamp = 0;
  53882. this.lodMaxClamp = 32;
  53883. this.compare = undefined;
  53884. this.maxAnisotropy = 1;
  53885. }
  53886. }
  53887. /**
  53888. * Reusable descriptor for `GPUTexelCopyTextureInfo`, the texture side of
  53889. * `GPUCommandEncoder.copyTextureToTexture()`, `copyTextureToBuffer()` and
  53890. * `GPUQueue.writeTexture()`.
  53891. *
  53892. * @private
  53893. */
  53894. class GPUTexelCopyTextureInfo {
  53895. constructor() {
  53896. /**
  53897. * The target texture.
  53898. *
  53899. * @type {?GPUTexture}
  53900. * @default null
  53901. */
  53902. this.texture = null;
  53903. /**
  53904. * The mipmap level of the texture.
  53905. *
  53906. * @type {number}
  53907. * @default 0
  53908. */
  53909. this.mipLevel = 0;
  53910. /**
  53911. * The origin offset within the texture.
  53912. *
  53913. * @type {{x: number, y: number, z: number}}
  53914. */
  53915. this.origin = { x: 0, y: 0, z: 0 };
  53916. /**
  53917. * Which aspect of the texture is referenced.
  53918. *
  53919. * @type {string}
  53920. * @default 'all'
  53921. */
  53922. this.aspect = 'all';
  53923. }
  53924. /**
  53925. * Resets the descriptor to its default state.
  53926. */
  53927. reset() {
  53928. this.texture = null;
  53929. this.mipLevel = 0;
  53930. this.origin.x = 0;
  53931. this.origin.y = 0;
  53932. this.origin.z = 0;
  53933. this.aspect = 'all';
  53934. }
  53935. }
  53936. /**
  53937. * Reusable descriptor for `GPUTexelCopyBufferInfo`, the buffer side of
  53938. * `GPUCommandEncoder.copyTextureToBuffer()` and `copyBufferToTexture()`.
  53939. *
  53940. * @private
  53941. */
  53942. class GPUTexelCopyBufferInfo {
  53943. constructor() {
  53944. /**
  53945. * The target buffer.
  53946. *
  53947. * @type {?GPUBuffer}
  53948. * @default null
  53949. */
  53950. this.buffer = null;
  53951. /**
  53952. * The byte offset within the buffer where the texel data begins.
  53953. *
  53954. * @type {number}
  53955. * @default 0
  53956. */
  53957. this.offset = 0;
  53958. /**
  53959. * The stride, in bytes, between rows of texel blocks.
  53960. *
  53961. * @type {number|undefined}
  53962. */
  53963. this.bytesPerRow = undefined;
  53964. /**
  53965. * The number of texel block rows per single image of the texture.
  53966. *
  53967. * @type {number|undefined}
  53968. */
  53969. this.rowsPerImage = undefined;
  53970. }
  53971. /**
  53972. * Resets the descriptor to its default state.
  53973. */
  53974. reset() {
  53975. this.buffer = null;
  53976. this.offset = 0;
  53977. this.bytesPerRow = undefined;
  53978. this.rowsPerImage = undefined;
  53979. }
  53980. }
  53981. /**
  53982. * Reusable descriptor for `GPUTexelCopyBufferLayout`, the data-layout argument
  53983. * to `GPUQueue.writeTexture()`.
  53984. *
  53985. * @private
  53986. */
  53987. class GPUTexelCopyBufferLayout {
  53988. constructor() {
  53989. /**
  53990. * The byte offset within the source data where the texel data begins.
  53991. *
  53992. * @type {number}
  53993. * @default 0
  53994. */
  53995. this.offset = 0;
  53996. /**
  53997. * The stride, in bytes, between rows of texel blocks.
  53998. *
  53999. * @type {number|undefined}
  54000. */
  54001. this.bytesPerRow = undefined;
  54002. /**
  54003. * The number of texel block rows per single image of the texture.
  54004. *
  54005. * @type {number|undefined}
  54006. */
  54007. this.rowsPerImage = undefined;
  54008. }
  54009. /**
  54010. * Resets the descriptor to its default state.
  54011. */
  54012. reset() {
  54013. this.offset = 0;
  54014. this.bytesPerRow = undefined;
  54015. this.rowsPerImage = undefined;
  54016. }
  54017. }
  54018. /**
  54019. * Reusable descriptor for `GPUCopyExternalImageSourceInfo`, the source argument
  54020. * to `GPUQueue.copyExternalImageToTexture()`.
  54021. *
  54022. * @private
  54023. */
  54024. class GPUCopyExternalImageSourceInfo {
  54025. constructor() {
  54026. /**
  54027. * The image-like source.
  54028. *
  54029. * @type {?(ImageBitmap|ImageData|HTMLImageElement|HTMLVideoElement|VideoFrame|HTMLCanvasElement|OffscreenCanvas)}
  54030. * @default null
  54031. */
  54032. this.source = null;
  54033. /**
  54034. * The origin offset within the source.
  54035. *
  54036. * @type {{x: number, y: number}}
  54037. */
  54038. this.origin = { x: 0, y: 0 };
  54039. /**
  54040. * Whether the source is flipped vertically before copying.
  54041. *
  54042. * @type {boolean}
  54043. * @default false
  54044. */
  54045. this.flipY = false;
  54046. }
  54047. /**
  54048. * Resets the descriptor to its default state.
  54049. */
  54050. reset() {
  54051. this.source = null;
  54052. this.origin.x = 0;
  54053. this.origin.y = 0;
  54054. this.flipY = false;
  54055. }
  54056. }
  54057. /**
  54058. * Reusable descriptor for `GPUCopyExternalImageDestInfo`, the destination
  54059. * argument to `GPUQueue.copyExternalImageToTexture()`.
  54060. *
  54061. * @private
  54062. * @augments GPUTexelCopyTextureInfo
  54063. */
  54064. class GPUCopyExternalImageDestInfo extends GPUTexelCopyTextureInfo {
  54065. constructor() {
  54066. super();
  54067. /**
  54068. * The predefined color space the destination texture is interpreted in.
  54069. *
  54070. * @type {string}
  54071. * @default 'srgb'
  54072. */
  54073. this.colorSpace = 'srgb';
  54074. /**
  54075. * Whether the destination texture has premultiplied alpha.
  54076. *
  54077. * @type {boolean}
  54078. * @default false
  54079. */
  54080. this.premultipliedAlpha = false;
  54081. }
  54082. /**
  54083. * Resets the descriptor to its default state.
  54084. */
  54085. reset() {
  54086. super.reset();
  54087. this.colorSpace = 'srgb';
  54088. this.premultipliedAlpha = false;
  54089. }
  54090. }
  54091. /**
  54092. * Reusable descriptor for `GPUExtent3D` in its dictionary form, used by
  54093. * `GPUQueue.writeTexture()`, `GPUQueue.copyExternalImageToTexture()` and
  54094. * the various `GPUCommandEncoder` copy methods.
  54095. *
  54096. * @private
  54097. */
  54098. class GPUExtent3D {
  54099. constructor() {
  54100. /**
  54101. * The width of the extent.
  54102. *
  54103. * @type {number}
  54104. * @default 0
  54105. */
  54106. this.width = 0;
  54107. /**
  54108. * The height of the extent.
  54109. *
  54110. * @type {number}
  54111. * @default 1
  54112. */
  54113. this.height = 1;
  54114. /**
  54115. * The depth (for 3D textures) or number of array layers.
  54116. *
  54117. * @type {number}
  54118. * @default 1
  54119. */
  54120. this.depthOrArrayLayers = 1;
  54121. }
  54122. /**
  54123. * Resets the descriptor to its default state.
  54124. */
  54125. reset() {
  54126. this.width = 0;
  54127. this.height = 1;
  54128. this.depthOrArrayLayers = 1;
  54129. }
  54130. }
  54131. const _bufferDescriptor$4 = new GPUBufferDescriptor();
  54132. const _commandEncoderDescriptor$3 = new GPUCommandEncoderDescriptor();
  54133. const _samplerDescriptor = new GPUSamplerDescriptor();
  54134. const _texelCopyTextureInfo = new GPUTexelCopyTextureInfo();
  54135. const _texelCopyBufferInfo = new GPUTexelCopyBufferInfo();
  54136. const _texelCopyBufferLayout = new GPUTexelCopyBufferLayout();
  54137. const _copyExternalImageSourceInfo = new GPUCopyExternalImageSourceInfo();
  54138. const _copyExternalImageDestInfo = new GPUCopyExternalImageDestInfo();
  54139. const _textureDescriptor = new GPUTextureDescriptor();
  54140. const _extent3D$1 = new GPUExtent3D();
  54141. const _compareToWebGPU = {
  54142. [ NeverCompare ]: 'never',
  54143. [ LessCompare ]: 'less',
  54144. [ EqualCompare ]: 'equal',
  54145. [ LessEqualCompare ]: 'less-equal',
  54146. [ GreaterCompare ]: 'greater',
  54147. [ GreaterEqualCompare ]: 'greater-equal',
  54148. [ AlwaysCompare ]: 'always',
  54149. [ NotEqualCompare ]: 'not-equal'
  54150. };
  54151. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  54152. function writeTextureLayer( device, textureGPU, mipLevel, layerIndex, mipmap, bytesPerImage, bytesPerRow, rowsPerImage, textureWidth, textureHeight ) {
  54153. _texelCopyTextureInfo.texture = textureGPU;
  54154. _texelCopyTextureInfo.mipLevel = mipLevel;
  54155. _texelCopyTextureInfo.origin.z = layerIndex;
  54156. _texelCopyBufferLayout.offset = layerIndex * bytesPerImage;
  54157. _texelCopyBufferLayout.bytesPerRow = bytesPerRow;
  54158. _texelCopyBufferLayout.rowsPerImage = rowsPerImage;
  54159. _extent3D$1.width = textureWidth;
  54160. _extent3D$1.height = textureHeight;
  54161. device.queue.writeTexture(
  54162. _texelCopyTextureInfo,
  54163. mipmap.data,
  54164. _texelCopyBufferLayout,
  54165. _extent3D$1
  54166. );
  54167. _texelCopyTextureInfo.reset();
  54168. _texelCopyBufferLayout.reset();
  54169. _extent3D$1.reset();
  54170. }
  54171. /**
  54172. * A WebGPU backend utility module for managing textures.
  54173. *
  54174. * @private
  54175. */
  54176. class WebGPUTextureUtils {
  54177. /**
  54178. * Constructs a new utility object.
  54179. *
  54180. * @param {WebGPUBackend} backend - The WebGPU backend.
  54181. */
  54182. constructor( backend ) {
  54183. /**
  54184. * A reference to the WebGPU backend.
  54185. *
  54186. * @type {WebGPUBackend}
  54187. */
  54188. this.backend = backend;
  54189. /**
  54190. * A reference to the pass utils.
  54191. *
  54192. * @type {?WebGPUTexturePassUtils}
  54193. * @default null
  54194. */
  54195. this._passUtils = null;
  54196. /**
  54197. * A dictionary for managing default textures. The key
  54198. * is the texture format, the value the texture object.
  54199. *
  54200. * @type {Object<string,Texture>}
  54201. */
  54202. this.defaultTexture = {};
  54203. /**
  54204. * A dictionary for managing default cube textures. The key
  54205. * is the texture format, the value the texture object.
  54206. *
  54207. * @type {Object<string,CubeTexture>}
  54208. */
  54209. this.defaultCubeTexture = {};
  54210. /**
  54211. * A default video frame.
  54212. *
  54213. * @type {?VideoFrame}
  54214. * @default null
  54215. */
  54216. this.defaultVideoFrame = null;
  54217. /**
  54218. * A cache of shared texture samplers.
  54219. *
  54220. * @type {Map<string, Object>}
  54221. */
  54222. this._samplerCache = new Map();
  54223. }
  54224. /**
  54225. * Creates a GPU sampler for the given texture.
  54226. *
  54227. * @param {Texture} texture - The texture to create the sampler for.
  54228. * @param {TextureNode} textureNode - The texture node to update the sampler with.
  54229. * @return {string} The current sampler key.
  54230. */
  54231. updateSampler( texture, textureNode ) {
  54232. const backend = this.backend;
  54233. const samplerKey = texture.minFilter + '-' + texture.magFilter + '-' +
  54234. texture.wrapS + '-' + texture.wrapT + '-' + ( texture.wrapR || '0' ) + '-' +
  54235. texture.anisotropy + '-' + ( texture.isDepthTexture === true ? 1 : 0 ) + '-' +
  54236. ( texture.compareFunction !== null && textureNode.compareNode !== null ? texture.compareFunction : 0 );
  54237. let samplerData = this._samplerCache.get( samplerKey );
  54238. if ( samplerData === undefined ) {
  54239. _samplerDescriptor.addressModeU = this._convertAddressMode( texture.wrapS );
  54240. _samplerDescriptor.addressModeV = this._convertAddressMode( texture.wrapT );
  54241. _samplerDescriptor.addressModeW = this._convertAddressMode( texture.wrapR );
  54242. _samplerDescriptor.magFilter = this._convertFilterMode( texture.magFilter );
  54243. _samplerDescriptor.minFilter = this._convertFilterMode( texture.minFilter );
  54244. _samplerDescriptor.mipmapFilter = this._convertMipmapFilterMode( texture.minFilter );
  54245. // Depth textures without compare function must use non-filtering (nearest) sampling
  54246. if ( texture.isDepthTexture && ( texture.compareFunction === null || textureNode.compareNode === null ) ) {
  54247. _samplerDescriptor.magFilter = GPUFilterMode.Nearest;
  54248. _samplerDescriptor.minFilter = GPUFilterMode.Nearest;
  54249. _samplerDescriptor.mipmapFilter = GPUFilterMode.Nearest;
  54250. }
  54251. // anisotropy can only be used when all filter modes are set to linear.
  54252. if ( _samplerDescriptor.magFilter === GPUFilterMode.Linear && _samplerDescriptor.minFilter === GPUFilterMode.Linear && _samplerDescriptor.mipmapFilter === GPUFilterMode.Linear ) {
  54253. _samplerDescriptor.maxAnisotropy = texture.anisotropy;
  54254. }
  54255. if ( texture.isDepthTexture && texture.compareFunction !== null && textureNode.compareNode !== null && backend.hasCompatibility( Compatibility.TEXTURE_COMPARE ) ) {
  54256. _samplerDescriptor.compare = _compareToWebGPU[ texture.compareFunction ];
  54257. }
  54258. const sampler = backend.device.createSampler( _samplerDescriptor );
  54259. _samplerDescriptor.reset();
  54260. samplerData = { sampler, usedTimes: 0 };
  54261. this._samplerCache.set( samplerKey, samplerData );
  54262. }
  54263. const textureData = backend.get( texture );
  54264. if ( textureData.sampler !== samplerData.sampler ) {
  54265. // check if previous sampler is unused so it can be deleted
  54266. if ( textureData.sampler !== undefined ) {
  54267. const oldSamplerData = this._samplerCache.get( textureData.samplerKey );
  54268. oldSamplerData.usedTimes --;
  54269. if ( oldSamplerData.usedTimes === 0 ) {
  54270. this._samplerCache.delete( textureData.samplerKey );
  54271. }
  54272. }
  54273. // update to new sampler data
  54274. textureData.samplerKey = samplerKey;
  54275. textureData.sampler = samplerData.sampler;
  54276. samplerData.usedTimes ++;
  54277. }
  54278. return samplerKey;
  54279. }
  54280. /**
  54281. * Creates a default texture for the given texture that can be used
  54282. * as a placeholder until the actual texture is ready for usage.
  54283. *
  54284. * @param {Texture} texture - The texture to create a default texture for.
  54285. */
  54286. createDefaultTexture( texture ) {
  54287. let textureGPU;
  54288. const format = getFormat( texture, this.backend.device );
  54289. if ( texture.isCubeTexture ) {
  54290. textureGPU = this._getDefaultCubeTextureGPU( format );
  54291. } else {
  54292. textureGPU = this._getDefaultTextureGPU( format );
  54293. }
  54294. this.backend.get( texture ).texture = textureGPU;
  54295. }
  54296. /**
  54297. * Defines a texture on the GPU for the given texture object.
  54298. *
  54299. * @param {Texture} texture - The texture.
  54300. * @param {Object} [options={}] - Optional configuration parameter.
  54301. */
  54302. createTexture( texture, options = {} ) {
  54303. const backend = this.backend;
  54304. const textureData = backend.get( texture );
  54305. if ( textureData.initialized ) {
  54306. // Skip creation for external XR textures - they are already set up
  54307. if ( textureData.externalTexture === true ) {
  54308. return;
  54309. }
  54310. throw new Error( 'THREE.WebGPUTextureUtils: Texture already initialized.' );
  54311. }
  54312. if ( texture.isExternalTexture ) {
  54313. textureData.texture = texture.sourceTexture;
  54314. textureData.initialized = true;
  54315. return;
  54316. }
  54317. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  54318. if ( options.levels === undefined ) options.levels = 1;
  54319. if ( options.depth === undefined ) options.depth = 1;
  54320. const { width, height, depth, levels } = options;
  54321. if ( texture.isFramebufferTexture ) {
  54322. if ( options.renderTarget ) {
  54323. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  54324. } else {
  54325. options.format = this.backend.utils.getPreferredCanvasFormat();
  54326. }
  54327. }
  54328. const dimension = this._getDimension( texture );
  54329. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  54330. textureData.format = format;
  54331. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  54332. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  54333. if ( texture.isStorageTexture === true ) {
  54334. usage |= GPUTextureUsage.STORAGE_BINDING;
  54335. }
  54336. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true && format !== GPUTextureFormat.RGB9E5UFloat ) {
  54337. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  54338. }
  54339. const textureDescriptorGPU = new GPUTextureDescriptor();
  54340. textureDescriptorGPU.label = texture.name;
  54341. textureDescriptorGPU.size.width = width;
  54342. textureDescriptorGPU.size.height = height;
  54343. textureDescriptorGPU.size.depthOrArrayLayers = depth;
  54344. textureDescriptorGPU.mipLevelCount = levels;
  54345. textureDescriptorGPU.sampleCount = primarySamples;
  54346. textureDescriptorGPU.dimension = dimension;
  54347. textureDescriptorGPU.format = format;
  54348. textureDescriptorGPU.usage = usage;
  54349. // texture creation
  54350. if ( format === undefined ) {
  54351. warn( 'WebGPURenderer: Texture format not supported.' );
  54352. this.createDefaultTexture( texture );
  54353. return;
  54354. }
  54355. if ( texture.isCubeTexture ) {
  54356. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  54357. }
  54358. try {
  54359. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  54360. } catch ( e ) {
  54361. warn( 'WebGPURenderer: Failed to create texture with descriptor:', textureDescriptorGPU );
  54362. this.createDefaultTexture( texture );
  54363. return;
  54364. }
  54365. if ( isMSAA ) {
  54366. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  54367. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  54368. msaaTextureDescriptorGPU.sampleCount = samples;
  54369. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  54370. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  54371. }
  54372. textureData.initialized = true;
  54373. textureData.textureDescriptorGPU = textureDescriptorGPU;
  54374. }
  54375. /**
  54376. * Destroys the GPU data for the given texture object.
  54377. *
  54378. * @param {Texture} texture - The texture.
  54379. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  54380. */
  54381. destroyTexture( texture, isDefaultTexture = false ) {
  54382. const backend = this.backend;
  54383. const textureData = backend.get( texture );
  54384. if ( textureData.texture !== undefined && isDefaultTexture === false ) textureData.texture.destroy();
  54385. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  54386. backend.delete( texture );
  54387. }
  54388. /**
  54389. * Generates mipmaps for the given texture.
  54390. *
  54391. * @param {Texture} texture - The texture.
  54392. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  54393. */
  54394. generateMipmaps( texture, encoder = null ) {
  54395. const textureData = this.backend.get( texture );
  54396. this._generateMipmaps( textureData.texture, encoder );
  54397. }
  54398. /**
  54399. * Returns the color buffer representing the color
  54400. * attachment of the default framebuffer.
  54401. *
  54402. * @return {GPUTexture} The color buffer.
  54403. */
  54404. getColorBuffer() {
  54405. const backend = this.backend;
  54406. const canvasTarget = backend.renderer.getCanvasTarget();
  54407. const { width, height } = backend.getDrawingBufferSize();
  54408. const samples = backend.renderer.currentSamples;
  54409. const colorTexture = canvasTarget.colorTexture;
  54410. const colorTextureData = backend.get( colorTexture );
  54411. if ( colorTexture.width === width && colorTexture.height === height && colorTexture.samples === samples ) {
  54412. return colorTextureData.texture;
  54413. }
  54414. // recreate
  54415. let colorBuffer = colorTextureData.texture;
  54416. if ( colorBuffer ) colorBuffer.destroy();
  54417. _textureDescriptor.label = 'colorBuffer';
  54418. _textureDescriptor.size.width = width;
  54419. _textureDescriptor.size.height = height;
  54420. _textureDescriptor.sampleCount = backend.utils.getSampleCount( backend.renderer.currentSamples );
  54421. _textureDescriptor.format = backend.utils.getPreferredCanvasFormat();
  54422. _textureDescriptor.usage = GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC;
  54423. colorBuffer = backend.device.createTexture( _textureDescriptor );
  54424. _textureDescriptor.reset();
  54425. //
  54426. colorTexture.source.width = width;
  54427. colorTexture.source.height = height;
  54428. colorTexture.samples = samples;
  54429. colorTextureData.texture = colorBuffer;
  54430. return colorBuffer;
  54431. }
  54432. /**
  54433. * Returns the depth buffer representing the depth
  54434. * attachment of the default framebuffer.
  54435. *
  54436. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  54437. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  54438. * @return {GPUTexture} The depth buffer.
  54439. */
  54440. getDepthBuffer( depth = true, stencil = false ) {
  54441. const backend = this.backend;
  54442. const canvasTarget = backend.renderer.getCanvasTarget();
  54443. const { width, height } = backend.getDrawingBufferSize();
  54444. const samples = backend.renderer.currentSamples;
  54445. const depthTexture = canvasTarget.depthTexture;
  54446. if ( depthTexture.width === width &&
  54447. depthTexture.height === height &&
  54448. depthTexture.samples === samples &&
  54449. depthTexture.depth === depth &&
  54450. depthTexture.stencil === stencil ) {
  54451. return backend.get( depthTexture ).texture;
  54452. }
  54453. //
  54454. const depthTextureGPU = backend.get( depthTexture ).texture;
  54455. let format, type;
  54456. if ( stencil ) {
  54457. format = DepthStencilFormat;
  54458. type = backend.renderer.reversedDepthBuffer === true ? FloatType : UnsignedInt248Type;
  54459. } else if ( depth ) {
  54460. format = DepthFormat;
  54461. type = backend.renderer.reversedDepthBuffer === true ? FloatType : UnsignedIntType;
  54462. }
  54463. if ( depthTextureGPU !== undefined ) {
  54464. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type && depthTexture.samples === samples ) {
  54465. return depthTextureGPU;
  54466. }
  54467. this.destroyTexture( depthTexture );
  54468. }
  54469. // recreate
  54470. depthTexture.name = 'depthBuffer';
  54471. depthTexture.format = format;
  54472. depthTexture.type = type;
  54473. depthTexture.image.width = width;
  54474. depthTexture.image.height = height;
  54475. depthTexture.samples = samples;
  54476. this.createTexture( depthTexture, { width, height } );
  54477. return backend.get( depthTexture ).texture;
  54478. }
  54479. /**
  54480. * Uploads the updated texture data to the GPU.
  54481. *
  54482. * @param {Texture} texture - The texture.
  54483. * @param {Object} [options={}] - Optional configuration parameter.
  54484. */
  54485. updateTexture( texture, options ) {
  54486. const textureData = this.backend.get( texture );
  54487. const mipmaps = texture.mipmaps;
  54488. const { textureDescriptorGPU } = textureData;
  54489. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  54490. return;
  54491. // transfer texture data
  54492. if ( texture.isDataTexture ) {
  54493. if ( mipmaps.length > 0 ) {
  54494. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  54495. const mipmap = mipmaps[ i ];
  54496. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  54497. }
  54498. } else {
  54499. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  54500. }
  54501. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  54502. if ( texture.layerUpdates && texture.layerUpdates.size > 0 ) {
  54503. for ( const layerIndex of texture.layerUpdates ) {
  54504. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, layerIndex, texture.flipY, layerIndex );
  54505. }
  54506. texture.clearLayerUpdates();
  54507. } else {
  54508. for ( let i = 0; i < options.image.depth; i ++ ) {
  54509. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  54510. }
  54511. }
  54512. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  54513. if ( texture.isCompressedArrayTexture && texture.layerUpdates.size > 0 ) {
  54514. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU, texture.layerUpdates );
  54515. texture.clearLayerUpdates();
  54516. } else {
  54517. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  54518. }
  54519. } else if ( texture.isCubeTexture ) {
  54520. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  54521. } else if ( texture.isHTMLTexture ) {
  54522. const device = this.backend.device;
  54523. const canvas = this.backend.renderer.domElement;
  54524. const image = texture.image;
  54525. if ( typeof device.queue.copyElementImageToTexture !== 'function' ) return;
  54526. // Skip the first frame — the element needs a paint record first.
  54527. if ( ! textureData.hasPaintCallback ) {
  54528. textureData.hasPaintCallback = true;
  54529. canvas.requestPaint();
  54530. return;
  54531. }
  54532. const width = textureDescriptorGPU.size.width;
  54533. const height = textureDescriptorGPU.size.height;
  54534. if ( device.queue.copyElementImageToTexture.length === 2 ) {
  54535. // Chrome 150+
  54536. device.queue.copyElementImageToTexture(
  54537. { source: image },
  54538. {
  54539. destination: { texture: textureData.texture },
  54540. width: width,
  54541. height: height
  54542. }
  54543. );
  54544. } else {
  54545. // Chrome 138 - 149
  54546. device.queue.copyElementImageToTexture(
  54547. image, width, height,
  54548. { texture: textureData.texture }
  54549. );
  54550. }
  54551. if ( texture.flipY ) {
  54552. this._flipY( textureData.texture, textureDescriptorGPU );
  54553. }
  54554. } else {
  54555. if ( mipmaps.length > 0 ) {
  54556. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  54557. const mipmap = mipmaps[ i ];
  54558. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  54559. }
  54560. } else {
  54561. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  54562. }
  54563. }
  54564. //
  54565. textureData.version = texture.version;
  54566. }
  54567. /**
  54568. * Returns texture data as a typed array.
  54569. *
  54570. * @async
  54571. * @param {Texture} texture - The texture to copy.
  54572. * @param {number} x - The x coordinate of the copy origin.
  54573. * @param {number} y - The y coordinate of the copy origin.
  54574. * @param {number} width - The width of the copy.
  54575. * @param {number} height - The height of the copy.
  54576. * @param {number} faceIndex - The face index.
  54577. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  54578. */
  54579. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  54580. const device = this.backend.device;
  54581. const textureData = this.backend.get( texture );
  54582. const textureGPU = textureData.texture;
  54583. const format = textureData.textureDescriptorGPU.format;
  54584. const bytesPerTexel = this._getBytesPerTexel( format );
  54585. let bytesPerRow = width * bytesPerTexel;
  54586. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  54587. _bufferDescriptor$4.size = ( ( height - 1 ) * bytesPerRow ) + ( width * bytesPerTexel ); // see https://github.com/mrdoob/three.js/issues/31658#issuecomment-3229442010
  54588. _bufferDescriptor$4.usage = GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ;
  54589. const readBuffer = device.createBuffer( _bufferDescriptor$4 );
  54590. _bufferDescriptor$4.reset();
  54591. const encoder = device.createCommandEncoder( _commandEncoderDescriptor$3 );
  54592. _texelCopyTextureInfo.texture = textureGPU;
  54593. _texelCopyTextureInfo.origin.x = x;
  54594. _texelCopyTextureInfo.origin.y = y;
  54595. _texelCopyTextureInfo.origin.z = faceIndex;
  54596. _texelCopyBufferInfo.buffer = readBuffer;
  54597. _texelCopyBufferInfo.bytesPerRow = bytesPerRow;
  54598. _extent3D$1.width = width;
  54599. _extent3D$1.height = height;
  54600. encoder.copyTextureToBuffer(
  54601. _texelCopyTextureInfo,
  54602. _texelCopyBufferInfo,
  54603. _extent3D$1
  54604. );
  54605. _texelCopyTextureInfo.reset();
  54606. _texelCopyBufferInfo.reset();
  54607. _extent3D$1.reset();
  54608. const typedArrayType = this._getTypedArrayType( format );
  54609. submit( device, encoder.finish() );
  54610. await readBuffer.mapAsync( GPUMapMode.READ );
  54611. const buffer = readBuffer.getMappedRange().slice();
  54612. readBuffer.destroy();
  54613. return new typedArrayType( buffer );
  54614. }
  54615. /**
  54616. * Frees all internal resources.
  54617. */
  54618. dispose() {
  54619. this._samplerCache.clear();
  54620. }
  54621. /**
  54622. * Returns the default GPU texture for the given format.
  54623. *
  54624. * @private
  54625. * @param {string} format - The GPU format.
  54626. * @return {GPUTexture} The GPU texture.
  54627. */
  54628. _getDefaultTextureGPU( format ) {
  54629. let defaultTexture = this.defaultTexture[ format ];
  54630. if ( defaultTexture === undefined ) {
  54631. const texture = new Texture();
  54632. texture.minFilter = NearestFilter;
  54633. texture.magFilter = NearestFilter;
  54634. this.createTexture( texture, { width: 1, height: 1, format } );
  54635. this.defaultTexture[ format ] = defaultTexture = texture;
  54636. }
  54637. return this.backend.get( defaultTexture ).texture;
  54638. }
  54639. /**
  54640. * Returns the default GPU cube texture for the given format.
  54641. *
  54642. * @private
  54643. * @param {string} format - The GPU format.
  54644. * @return {GPUTexture} The GPU texture.
  54645. */
  54646. _getDefaultCubeTextureGPU( format ) {
  54647. let defaultCubeTexture = this.defaultCubeTexture[ format ];
  54648. if ( defaultCubeTexture === undefined ) {
  54649. const texture = new CubeTexture();
  54650. texture.minFilter = NearestFilter;
  54651. texture.magFilter = NearestFilter;
  54652. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  54653. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  54654. }
  54655. return this.backend.get( defaultCubeTexture ).texture;
  54656. }
  54657. /**
  54658. * Uploads cube texture image data to the GPU memory.
  54659. *
  54660. * @private
  54661. * @param {CubeTexture} texture - The cube texture.
  54662. * @param {GPUTexture} textureGPU - The GPU texture.
  54663. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  54664. */
  54665. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  54666. const images = texture.images;
  54667. const mipmaps = texture.mipmaps;
  54668. for ( let i = 0; i < 6; i ++ ) {
  54669. const image = images[ i ];
  54670. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  54671. if ( image.isDataTexture ) {
  54672. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  54673. } else {
  54674. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  54675. }
  54676. for ( let j = 0; j < mipmaps.length; j ++ ) {
  54677. const mipmap = mipmaps[ j ];
  54678. const image = mipmap.images[ i ];
  54679. if ( image.isDataTexture ) {
  54680. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  54681. } else {
  54682. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  54683. }
  54684. }
  54685. }
  54686. }
  54687. /**
  54688. * Uploads texture image data to the GPU memory.
  54689. *
  54690. * @private
  54691. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  54692. * @param {GPUTexture} textureGPU - The GPU texture.
  54693. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  54694. * @param {number} originDepth - The origin depth.
  54695. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  54696. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  54697. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  54698. */
  54699. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  54700. const device = this.backend.device;
  54701. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  54702. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  54703. _copyExternalImageSourceInfo.source = image;
  54704. _copyExternalImageSourceInfo.flipY = flipY;
  54705. _copyExternalImageDestInfo.texture = textureGPU;
  54706. _copyExternalImageDestInfo.mipLevel = mipLevel;
  54707. _copyExternalImageDestInfo.origin.z = originDepth;
  54708. _copyExternalImageDestInfo.premultipliedAlpha = premultiplyAlpha;
  54709. _extent3D$1.width = width;
  54710. _extent3D$1.height = height;
  54711. try {
  54712. device.queue.copyExternalImageToTexture(
  54713. _copyExternalImageSourceInfo,
  54714. _copyExternalImageDestInfo,
  54715. _extent3D$1
  54716. );
  54717. // try/catch has been added to fix bad video frame data on certain devices, see #32391
  54718. } catch ( _ ) {
  54719. } finally {
  54720. _copyExternalImageSourceInfo.reset();
  54721. _copyExternalImageDestInfo.reset();
  54722. _extent3D$1.reset();
  54723. }
  54724. }
  54725. /**
  54726. * Returns the pass utils singleton.
  54727. *
  54728. * @private
  54729. * @return {WebGPUTexturePassUtils} The utils instance.
  54730. */
  54731. _getPassUtils() {
  54732. let passUtils = this._passUtils;
  54733. if ( passUtils === null ) {
  54734. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  54735. }
  54736. return passUtils;
  54737. }
  54738. /**
  54739. * Generates mipmaps for the given GPU texture.
  54740. *
  54741. * @private
  54742. * @param {GPUTexture} textureGPU - The GPU texture object.
  54743. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  54744. */
  54745. _generateMipmaps( textureGPU, encoder = null ) {
  54746. this._getPassUtils().generateMipmaps( textureGPU, encoder );
  54747. }
  54748. /**
  54749. * Flip the contents of the given GPU texture along its vertical axis.
  54750. *
  54751. * @private
  54752. * @param {GPUTexture} textureGPU - The GPU texture object.
  54753. * @param {Object} textureDescriptorGPU - The texture descriptor.
  54754. * @param {number} [originDepth=0] - The origin depth.
  54755. */
  54756. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  54757. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  54758. }
  54759. /**
  54760. * Uploads texture buffer data to the GPU memory.
  54761. *
  54762. * @private
  54763. * @param {Object} image - An object defining the image buffer data.
  54764. * @param {GPUTexture} textureGPU - The GPU texture.
  54765. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  54766. * @param {number} originDepth - The origin depth.
  54767. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  54768. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  54769. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  54770. */
  54771. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  54772. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  54773. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  54774. const device = this.backend.device;
  54775. const data = image.data;
  54776. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  54777. const bytesPerRow = image.width * bytesPerTexel;
  54778. _texelCopyTextureInfo.texture = textureGPU;
  54779. _texelCopyTextureInfo.mipLevel = mipLevel;
  54780. _texelCopyTextureInfo.origin.z = originDepth;
  54781. _texelCopyBufferLayout.offset = image.width * image.height * bytesPerTexel * depth;
  54782. _texelCopyBufferLayout.bytesPerRow = bytesPerRow;
  54783. _extent3D$1.width = image.width;
  54784. _extent3D$1.height = image.height;
  54785. device.queue.writeTexture(
  54786. _texelCopyTextureInfo,
  54787. data,
  54788. _texelCopyBufferLayout,
  54789. _extent3D$1
  54790. );
  54791. _texelCopyTextureInfo.reset();
  54792. _texelCopyBufferLayout.reset();
  54793. _extent3D$1.reset();
  54794. if ( flipY === true ) {
  54795. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  54796. }
  54797. }
  54798. /**
  54799. * Uploads compressed texture data to the GPU memory.
  54800. *
  54801. * @private
  54802. * @param {Array<Object>} mipmaps - An array with mipmap data.
  54803. * @param {GPUTexture} textureGPU - The GPU texture.
  54804. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  54805. * @param {?Set<number>} [layerUpdates=null] - The layer indices to update.
  54806. */
  54807. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU, layerUpdates = null ) {
  54808. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  54809. const device = this.backend.device;
  54810. const blockData = this._getBlockData( textureDescriptorGPU.format );
  54811. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  54812. const activeLayerUpdates = layerUpdates && layerUpdates.size > 0 ? layerUpdates : null;
  54813. for ( let i = 0; i < mipmaps.length; i ++ ) {
  54814. const mipmap = mipmaps[ i ];
  54815. const width = mipmap.width;
  54816. const height = mipmap.height;
  54817. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  54818. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  54819. const rowsPerImage = Math.ceil( height / blockData.height );
  54820. const bytesPerImage = bytesPerRow * rowsPerImage;
  54821. const textureWidth = Math.ceil( width / blockData.width ) * blockData.width;
  54822. const textureHeight = rowsPerImage * blockData.height;
  54823. if ( activeLayerUpdates !== null ) {
  54824. for ( const layerIndex of activeLayerUpdates ) {
  54825. writeTextureLayer( device, textureGPU, i, layerIndex, mipmap, bytesPerImage, bytesPerRow, rowsPerImage, textureWidth, textureHeight );
  54826. }
  54827. } else {
  54828. for ( let layerIndex = 0; layerIndex < depth; layerIndex ++ ) {
  54829. writeTextureLayer( device, textureGPU, i, layerIndex, mipmap, bytesPerImage, bytesPerRow, rowsPerImage, textureWidth, textureHeight );
  54830. }
  54831. }
  54832. }
  54833. }
  54834. /**
  54835. * This method is only relevant for compressed texture formats. It returns a block
  54836. * data descriptor for the given GPU compressed texture format.
  54837. *
  54838. * @private
  54839. * @param {string} format - The GPU compressed texture format.
  54840. * @return {Object} The block data descriptor.
  54841. */
  54842. _getBlockData( format ) {
  54843. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  54844. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  54845. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  54846. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  54847. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  54848. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  54849. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  54850. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  54851. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  54852. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  54853. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  54854. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  54855. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  54856. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  54857. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  54858. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  54859. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  54860. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  54861. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  54862. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  54863. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  54864. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  54865. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  54866. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  54867. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  54868. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  54869. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  54870. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  54871. }
  54872. /**
  54873. * Converts the three.js uv wrapping constants to GPU address mode constants.
  54874. *
  54875. * @private
  54876. * @param {number} value - The three.js constant defining a uv wrapping mode.
  54877. * @return {string} The GPU address mode.
  54878. */
  54879. _convertAddressMode( value ) {
  54880. let addressMode = GPUAddressMode.ClampToEdge;
  54881. if ( value === RepeatWrapping ) {
  54882. addressMode = GPUAddressMode.Repeat;
  54883. } else if ( value === MirroredRepeatWrapping ) {
  54884. addressMode = GPUAddressMode.MirrorRepeat;
  54885. }
  54886. return addressMode;
  54887. }
  54888. /**
  54889. * Converts the three.js filter constants to GPU filter constants.
  54890. *
  54891. * @private
  54892. * @param {number} value - The three.js constant defining a filter mode.
  54893. * @return {string} The GPU filter mode.
  54894. */
  54895. _convertFilterMode( value ) {
  54896. let filterMode = GPUFilterMode.Linear;
  54897. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  54898. filterMode = GPUFilterMode.Nearest;
  54899. }
  54900. return filterMode;
  54901. }
  54902. /**
  54903. * Converts the three.js filter constants to a GPU mipmap filter constant.
  54904. * Unlike `_convertFilterMode`, this extracts the between-mip-level filtering
  54905. * axis from the combined three.js constant rather than the within-level axis.
  54906. *
  54907. * @private
  54908. * @param {number} value - The three.js constant defining a filter mode.
  54909. * @return {string} The GPU mipmap filter mode.
  54910. */
  54911. _convertMipmapFilterMode( value ) {
  54912. if ( value === NearestMipmapLinearFilter || value === LinearMipmapLinearFilter ) {
  54913. return GPUFilterMode.Linear;
  54914. }
  54915. return GPUFilterMode.Nearest;
  54916. }
  54917. /**
  54918. * Returns the bytes-per-texel value for the given GPU texture format.
  54919. *
  54920. * @private
  54921. * @param {string} format - The GPU texture format.
  54922. * @return {number} The bytes-per-texel.
  54923. */
  54924. _getBytesPerTexel( format ) {
  54925. // 8-bit formats
  54926. if ( format === GPUTextureFormat.R8Unorm ||
  54927. format === GPUTextureFormat.R8Snorm ||
  54928. format === GPUTextureFormat.R8Uint ||
  54929. format === GPUTextureFormat.R8Sint ) return 1;
  54930. // 16-bit formats
  54931. if ( format === GPUTextureFormat.R16Uint ||
  54932. format === GPUTextureFormat.R16Sint ||
  54933. format === GPUTextureFormat.R16Float ||
  54934. format === GPUTextureFormat.RG8Unorm ||
  54935. format === GPUTextureFormat.RG8Snorm ||
  54936. format === GPUTextureFormat.RG8Uint ||
  54937. format === GPUTextureFormat.RG8Sint ||
  54938. format === GPUTextureFormat.R16Unorm ||
  54939. format === GPUTextureFormat.R16Snorm ) return 2;
  54940. // 32-bit formats
  54941. if ( format === GPUTextureFormat.R32Uint ||
  54942. format === GPUTextureFormat.R32Sint ||
  54943. format === GPUTextureFormat.R32Float ||
  54944. format === GPUTextureFormat.RG16Uint ||
  54945. format === GPUTextureFormat.RG16Sint ||
  54946. format === GPUTextureFormat.RG16Float ||
  54947. format === GPUTextureFormat.RGBA8Unorm ||
  54948. format === GPUTextureFormat.RGBA8UnormSRGB ||
  54949. format === GPUTextureFormat.RGBA8Snorm ||
  54950. format === GPUTextureFormat.RGBA8Uint ||
  54951. format === GPUTextureFormat.RGBA8Sint ||
  54952. format === GPUTextureFormat.BGRA8Unorm ||
  54953. format === GPUTextureFormat.BGRA8UnormSRGB ||
  54954. format === GPUTextureFormat.RG16Unorm ||
  54955. format === GPUTextureFormat.RG16Snorm ||
  54956. // Packed 32-bit formats
  54957. format === GPUTextureFormat.RGB9E5UFloat ||
  54958. format === GPUTextureFormat.RGB10A2Unorm ||
  54959. format === GPUTextureFormat.RG11B10UFloat ||
  54960. format === GPUTextureFormat.Depth32Float ||
  54961. format === GPUTextureFormat.Depth24Plus ||
  54962. format === GPUTextureFormat.Depth24PlusStencil8 ||
  54963. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  54964. // 64-bit formats
  54965. if ( format === GPUTextureFormat.RG32Uint ||
  54966. format === GPUTextureFormat.RG32Sint ||
  54967. format === GPUTextureFormat.RG32Float ||
  54968. format === GPUTextureFormat.RGBA16Uint ||
  54969. format === GPUTextureFormat.RGBA16Sint ||
  54970. format === GPUTextureFormat.RGBA16Float ||
  54971. format === GPUTextureFormat.RGBA16Unorm ||
  54972. format === GPUTextureFormat.RGBA16Snorm ) return 8;
  54973. // 128-bit formats
  54974. if ( format === GPUTextureFormat.RGBA32Uint ||
  54975. format === GPUTextureFormat.RGBA32Sint ||
  54976. format === GPUTextureFormat.RGBA32Float ) return 16;
  54977. }
  54978. /**
  54979. * Returns the corresponding typed array type for the given GPU texture format.
  54980. *
  54981. * @private
  54982. * @param {string} format - The GPU texture format.
  54983. * @return {TypedArray.constructor} The typed array type.
  54984. */
  54985. _getTypedArrayType( format ) {
  54986. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  54987. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  54988. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  54989. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  54990. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  54991. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  54992. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  54993. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  54994. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  54995. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  54996. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  54997. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  54998. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  54999. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  55000. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  55001. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  55002. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  55003. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  55004. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  55005. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  55006. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  55007. if ( format === GPUTextureFormat.R16Unorm ) return Uint16Array;
  55008. if ( format === GPUTextureFormat.R16Snorm ) return Int16Array;
  55009. if ( format === GPUTextureFormat.RG16Unorm ) return Uint16Array;
  55010. if ( format === GPUTextureFormat.RG16Snorm ) return Int16Array;
  55011. if ( format === GPUTextureFormat.RGBA16Unorm ) return Uint16Array;
  55012. if ( format === GPUTextureFormat.RGBA16Snorm ) return Int16Array;
  55013. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  55014. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  55015. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  55016. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  55017. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  55018. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  55019. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  55020. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  55021. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  55022. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  55023. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  55024. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  55025. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  55026. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  55027. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  55028. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  55029. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  55030. }
  55031. /**
  55032. * Returns the GPU dimensions for the given texture.
  55033. *
  55034. * @private
  55035. * @param {Texture} texture - The texture.
  55036. * @return {string} The GPU dimension.
  55037. */
  55038. _getDimension( texture ) {
  55039. let dimension;
  55040. if ( texture.is3DTexture || texture.isData3DTexture ) {
  55041. dimension = GPUTextureDimension.ThreeD;
  55042. } else {
  55043. dimension = GPUTextureDimension.TwoD;
  55044. }
  55045. return dimension;
  55046. }
  55047. }
  55048. /**
  55049. * Returns the GPU format for the given texture.
  55050. *
  55051. * @param {Texture} texture - The texture.
  55052. * @param {GPUDevice} [device] - The GPU device which is used for feature detection.
  55053. * @return {string} The GPU format.
  55054. */
  55055. function getFormat( texture, device ) {
  55056. const format = texture.format;
  55057. const type = texture.type;
  55058. const normalized = texture.normalized;
  55059. const colorSpace = texture.colorSpace;
  55060. const transfer = ColorManagement.getTransfer( colorSpace );
  55061. let formatGPU;
  55062. let textureFormatsTier1 = false;
  55063. if ( normalized ) {
  55064. textureFormatsTier1 = device.features.has( GPUFeatureName.TextureFormatsTier1 );
  55065. if ( textureFormatsTier1 === false ) {
  55066. warn( 'WebGPURenderer: Unable to use normalized textures without texture-formats-tier1 feature.' );
  55067. }
  55068. }
  55069. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  55070. switch ( format ) {
  55071. case RGB_S3TC_DXT1_Format:
  55072. case RGBA_S3TC_DXT1_Format:
  55073. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  55074. break;
  55075. case RGBA_S3TC_DXT3_Format:
  55076. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  55077. break;
  55078. case RGBA_S3TC_DXT5_Format:
  55079. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  55080. break;
  55081. case RED_RGTC1_Format:
  55082. formatGPU = GPUTextureFormat.BC4RUnorm;
  55083. break;
  55084. case SIGNED_RED_RGTC1_Format:
  55085. formatGPU = GPUTextureFormat.BC4RSnorm;
  55086. break;
  55087. case RED_GREEN_RGTC2_Format:
  55088. formatGPU = GPUTextureFormat.BC5RGUnorm;
  55089. break;
  55090. case SIGNED_RED_GREEN_RGTC2_Format:
  55091. formatGPU = GPUTextureFormat.BC5RGSnorm;
  55092. break;
  55093. case RGBA_BPTC_Format:
  55094. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC7RGBAUnormSRGB : GPUTextureFormat.BC7RGBAUnorm;
  55095. break;
  55096. case RGB_BPTC_SIGNED_Format:
  55097. formatGPU = GPUTextureFormat.BC6HRGBFloat;
  55098. break;
  55099. case RGB_BPTC_UNSIGNED_Format:
  55100. formatGPU = GPUTextureFormat.BC6HRGBUFloat;
  55101. break;
  55102. case RGB_ETC2_Format:
  55103. case RGB_ETC1_Format:
  55104. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  55105. break;
  55106. case RGBA_ETC2_EAC_Format:
  55107. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  55108. break;
  55109. case R11_EAC_Format:
  55110. formatGPU = GPUTextureFormat.EACR11Unorm;
  55111. break;
  55112. case SIGNED_R11_EAC_Format:
  55113. formatGPU = GPUTextureFormat.EACR11Snorm;
  55114. break;
  55115. case RG11_EAC_Format:
  55116. formatGPU = GPUTextureFormat.EACRG11Unorm;
  55117. break;
  55118. case SIGNED_RG11_EAC_Format:
  55119. formatGPU = GPUTextureFormat.EACRG11Snorm;
  55120. break;
  55121. case RGBA_ASTC_4x4_Format:
  55122. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  55123. break;
  55124. case RGBA_ASTC_5x4_Format:
  55125. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  55126. break;
  55127. case RGBA_ASTC_5x5_Format:
  55128. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  55129. break;
  55130. case RGBA_ASTC_6x5_Format:
  55131. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  55132. break;
  55133. case RGBA_ASTC_6x6_Format:
  55134. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  55135. break;
  55136. case RGBA_ASTC_8x5_Format:
  55137. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  55138. break;
  55139. case RGBA_ASTC_8x6_Format:
  55140. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  55141. break;
  55142. case RGBA_ASTC_8x8_Format:
  55143. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  55144. break;
  55145. case RGBA_ASTC_10x5_Format:
  55146. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  55147. break;
  55148. case RGBA_ASTC_10x6_Format:
  55149. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  55150. break;
  55151. case RGBA_ASTC_10x8_Format:
  55152. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  55153. break;
  55154. case RGBA_ASTC_10x10_Format:
  55155. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  55156. break;
  55157. case RGBA_ASTC_12x10_Format:
  55158. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  55159. break;
  55160. case RGBA_ASTC_12x12_Format:
  55161. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  55162. break;
  55163. case RGBAFormat:
  55164. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  55165. break;
  55166. default:
  55167. error( 'WebGPURenderer: Unsupported texture format.', format );
  55168. }
  55169. } else {
  55170. switch ( format ) {
  55171. case RGBAFormat:
  55172. switch ( type ) {
  55173. case ByteType:
  55174. formatGPU = GPUTextureFormat.RGBA8Snorm;
  55175. break;
  55176. case ShortType:
  55177. formatGPU = textureFormatsTier1 ? GPUTextureFormat.RGBA16Snorm : GPUTextureFormat.RGBA16Sint;
  55178. break;
  55179. case UnsignedShortType:
  55180. formatGPU = textureFormatsTier1 ? GPUTextureFormat.RGBA16Unorm : GPUTextureFormat.RGBA16Uint;
  55181. break;
  55182. case UnsignedIntType:
  55183. formatGPU = GPUTextureFormat.RGBA32Uint;
  55184. break;
  55185. case IntType:
  55186. formatGPU = GPUTextureFormat.RGBA32Sint;
  55187. break;
  55188. case UnsignedByteType:
  55189. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  55190. break;
  55191. case HalfFloatType:
  55192. formatGPU = GPUTextureFormat.RGBA16Float;
  55193. break;
  55194. case FloatType:
  55195. formatGPU = GPUTextureFormat.RGBA32Float;
  55196. break;
  55197. default:
  55198. error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  55199. }
  55200. break;
  55201. case RGBFormat:
  55202. switch ( type ) {
  55203. case UnsignedInt5999Type:
  55204. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  55205. break;
  55206. case UnsignedInt101111Type:
  55207. formatGPU = GPUTextureFormat.RG11B10UFloat;
  55208. break;
  55209. default:
  55210. error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  55211. }
  55212. break;
  55213. case RedFormat:
  55214. switch ( type ) {
  55215. case ByteType:
  55216. formatGPU = GPUTextureFormat.R8Snorm;
  55217. break;
  55218. case ShortType:
  55219. formatGPU = textureFormatsTier1 ? GPUTextureFormat.R16Snorm : GPUTextureFormat.R16Sint;
  55220. break;
  55221. case UnsignedShortType:
  55222. formatGPU = textureFormatsTier1 ? GPUTextureFormat.R16Unorm : GPUTextureFormat.R16Uint;
  55223. break;
  55224. case UnsignedIntType:
  55225. formatGPU = GPUTextureFormat.R32Uint;
  55226. break;
  55227. case IntType:
  55228. formatGPU = GPUTextureFormat.R32Sint;
  55229. break;
  55230. case UnsignedByteType:
  55231. formatGPU = GPUTextureFormat.R8Unorm;
  55232. break;
  55233. case HalfFloatType:
  55234. formatGPU = GPUTextureFormat.R16Float;
  55235. break;
  55236. case FloatType:
  55237. formatGPU = GPUTextureFormat.R32Float;
  55238. break;
  55239. default:
  55240. error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  55241. }
  55242. break;
  55243. case RGFormat:
  55244. switch ( type ) {
  55245. case ByteType:
  55246. formatGPU = GPUTextureFormat.RG8Snorm;
  55247. break;
  55248. case ShortType:
  55249. formatGPU = textureFormatsTier1 ? GPUTextureFormat.RG16Snorm : GPUTextureFormat.RG16Sint;
  55250. break;
  55251. case UnsignedShortType:
  55252. formatGPU = textureFormatsTier1 ? GPUTextureFormat.RG16Unorm : GPUTextureFormat.RG16Uint;
  55253. break;
  55254. case UnsignedIntType:
  55255. formatGPU = GPUTextureFormat.RG32Uint;
  55256. break;
  55257. case IntType:
  55258. formatGPU = GPUTextureFormat.RG32Sint;
  55259. break;
  55260. case UnsignedByteType:
  55261. formatGPU = GPUTextureFormat.RG8Unorm;
  55262. break;
  55263. case HalfFloatType:
  55264. formatGPU = GPUTextureFormat.RG16Float;
  55265. break;
  55266. case FloatType:
  55267. formatGPU = GPUTextureFormat.RG32Float;
  55268. break;
  55269. default:
  55270. error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  55271. }
  55272. break;
  55273. case DepthFormat:
  55274. switch ( type ) {
  55275. case UnsignedShortType:
  55276. formatGPU = GPUTextureFormat.Depth16Unorm;
  55277. break;
  55278. case UnsignedIntType:
  55279. formatGPU = GPUTextureFormat.Depth24Plus;
  55280. break;
  55281. case FloatType:
  55282. formatGPU = GPUTextureFormat.Depth32Float;
  55283. break;
  55284. default:
  55285. error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  55286. }
  55287. break;
  55288. case DepthStencilFormat:
  55289. switch ( type ) {
  55290. case UnsignedInt248Type:
  55291. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  55292. break;
  55293. case FloatType:
  55294. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  55295. error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  55296. }
  55297. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  55298. break;
  55299. default:
  55300. error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  55301. }
  55302. break;
  55303. case RedIntegerFormat:
  55304. switch ( type ) {
  55305. case IntType:
  55306. formatGPU = GPUTextureFormat.R32Sint;
  55307. break;
  55308. case UnsignedIntType:
  55309. formatGPU = GPUTextureFormat.R32Uint;
  55310. break;
  55311. default:
  55312. error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  55313. }
  55314. break;
  55315. case RGIntegerFormat:
  55316. switch ( type ) {
  55317. case IntType:
  55318. formatGPU = GPUTextureFormat.RG32Sint;
  55319. break;
  55320. case UnsignedIntType:
  55321. formatGPU = GPUTextureFormat.RG32Uint;
  55322. break;
  55323. default:
  55324. error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  55325. }
  55326. break;
  55327. case RGBAIntegerFormat:
  55328. switch ( type ) {
  55329. case IntType:
  55330. formatGPU = GPUTextureFormat.RGBA32Sint;
  55331. break;
  55332. case UnsignedIntType:
  55333. formatGPU = GPUTextureFormat.RGBA32Uint;
  55334. break;
  55335. default:
  55336. error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  55337. }
  55338. break;
  55339. default:
  55340. error( 'WebGPURenderer: Unsupported texture format.', format );
  55341. }
  55342. }
  55343. return formatGPU;
  55344. }
  55345. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  55346. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  55347. const wgslTypeLib$1 = {
  55348. 'f32': 'float',
  55349. 'i32': 'int',
  55350. 'u32': 'uint',
  55351. 'bool': 'bool',
  55352. 'vec2<f32>': 'vec2',
  55353. 'vec2<i32>': 'ivec2',
  55354. 'vec2<u32>': 'uvec2',
  55355. 'vec2<bool>': 'bvec2',
  55356. 'vec2f': 'vec2',
  55357. 'vec2i': 'ivec2',
  55358. 'vec2u': 'uvec2',
  55359. 'vec2b': 'bvec2',
  55360. 'vec3<f32>': 'vec3',
  55361. 'vec3<i32>': 'ivec3',
  55362. 'vec3<u32>': 'uvec3',
  55363. 'vec3<bool>': 'bvec3',
  55364. 'vec3f': 'vec3',
  55365. 'vec3i': 'ivec3',
  55366. 'vec3u': 'uvec3',
  55367. 'vec3b': 'bvec3',
  55368. 'vec4<f32>': 'vec4',
  55369. 'vec4<i32>': 'ivec4',
  55370. 'vec4<u32>': 'uvec4',
  55371. 'vec4<bool>': 'bvec4',
  55372. 'vec4f': 'vec4',
  55373. 'vec4i': 'ivec4',
  55374. 'vec4u': 'uvec4',
  55375. 'vec4b': 'bvec4',
  55376. 'mat2x2<f32>': 'mat2',
  55377. 'mat2x2f': 'mat2',
  55378. 'mat3x3<f32>': 'mat3',
  55379. 'mat3x3f': 'mat3',
  55380. 'mat4x4<f32>': 'mat4',
  55381. 'mat4x4f': 'mat4',
  55382. 'sampler': 'sampler',
  55383. 'texture_1d': 'texture',
  55384. 'texture_2d': 'texture',
  55385. 'texture_2d_array': 'texture',
  55386. 'texture_multisampled_2d': 'cubeTexture',
  55387. 'texture_depth_2d': 'depthTexture',
  55388. 'texture_depth_2d_array': 'depthTexture',
  55389. 'texture_depth_multisampled_2d': 'depthTexture',
  55390. 'texture_depth_cube': 'depthTexture',
  55391. 'texture_depth_cube_array': 'depthTexture',
  55392. 'texture_3d': 'texture3D',
  55393. 'texture_cube': 'cubeTexture',
  55394. 'texture_cube_array': 'cubeTexture',
  55395. 'texture_storage_1d': 'storageTexture',
  55396. 'texture_storage_2d': 'storageTexture',
  55397. 'texture_storage_2d_array': 'storageTexture',
  55398. 'texture_storage_3d': 'storageTexture'
  55399. };
  55400. const parse = ( source ) => {
  55401. source = source.trim();
  55402. const declaration = source.match( declarationRegexp );
  55403. if ( declaration !== null && declaration.length === 4 ) {
  55404. const inputsCode = declaration[ 2 ];
  55405. const propsMatches = [];
  55406. let match = null;
  55407. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  55408. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  55409. }
  55410. // Process matches to correctly pair names and types
  55411. const inputs = [];
  55412. for ( let i = 0; i < propsMatches.length; i ++ ) {
  55413. const { name, type } = propsMatches[ i ];
  55414. let resolvedType = type;
  55415. if ( resolvedType.startsWith( 'ptr' ) ) {
  55416. resolvedType = 'pointer';
  55417. } else {
  55418. if ( resolvedType.startsWith( 'texture' ) ) {
  55419. resolvedType = type.split( '<' )[ 0 ];
  55420. }
  55421. resolvedType = wgslTypeLib$1[ resolvedType ];
  55422. }
  55423. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  55424. }
  55425. const blockCode = source.substring( declaration[ 0 ].length );
  55426. const outputType = declaration[ 3 ] || 'void';
  55427. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  55428. const type = wgslTypeLib$1[ outputType ] || outputType;
  55429. return {
  55430. type,
  55431. inputs,
  55432. name,
  55433. inputsCode,
  55434. blockCode,
  55435. outputType
  55436. };
  55437. } else {
  55438. throw new Error( 'THREE.WGSLNodeFunction: Function is not a WGSL code.' );
  55439. }
  55440. };
  55441. /**
  55442. * This class represents a WSL node function.
  55443. *
  55444. * @augments NodeFunction
  55445. */
  55446. class WGSLNodeFunction extends NodeFunction {
  55447. /**
  55448. * Constructs a new WGSL node function.
  55449. *
  55450. * @param {string} source - The WGSL source.
  55451. */
  55452. constructor( source ) {
  55453. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  55454. super( type, inputs, name );
  55455. this.inputsCode = inputsCode;
  55456. this.blockCode = blockCode;
  55457. this.outputType = outputType;
  55458. }
  55459. /**
  55460. * This method returns the WGSL code of the node function.
  55461. *
  55462. * @param {string} [name=this.name] - The function's name.
  55463. * @return {string} The shader code.
  55464. */
  55465. getCode( name = this.name ) {
  55466. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  55467. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  55468. }
  55469. }
  55470. /**
  55471. * A WGSL node parser.
  55472. *
  55473. * @augments NodeParser
  55474. */
  55475. class WGSLNodeParser extends NodeParser {
  55476. /**
  55477. * The method parses the given WGSL code an returns a node function.
  55478. *
  55479. * @param {string} source - The WGSL code.
  55480. * @return {WGSLNodeFunction} A node function.
  55481. */
  55482. parseFunction( source ) {
  55483. return new WGSLNodeFunction( source );
  55484. }
  55485. }
  55486. const accessNames = {
  55487. [ NodeAccess.READ_ONLY ]: 'read',
  55488. [ NodeAccess.WRITE_ONLY ]: 'write',
  55489. [ NodeAccess.READ_WRITE ]: 'read_write'
  55490. };
  55491. const wrapNames = {
  55492. [ RepeatWrapping ]: 'repeat',
  55493. [ ClampToEdgeWrapping ]: 'clamp',
  55494. [ MirroredRepeatWrapping ]: 'mirror'
  55495. };
  55496. const gpuShaderStageLib = {
  55497. 'vertex': GPUShaderStage.VERTEX,
  55498. 'fragment': GPUShaderStage.FRAGMENT,
  55499. 'compute': GPUShaderStage.COMPUTE
  55500. };
  55501. const supports = {
  55502. instance: true,
  55503. swizzleAssign: false,
  55504. storageBuffer: true
  55505. };
  55506. const wgslFnOpLib = {
  55507. '^^': 'tsl_xor'
  55508. };
  55509. const wgslTypeLib = {
  55510. float: 'f32',
  55511. int: 'i32',
  55512. uint: 'u32',
  55513. bool: 'bool',
  55514. color: 'vec3<f32>',
  55515. vec2: 'vec2<f32>',
  55516. ivec2: 'vec2<i32>',
  55517. uvec2: 'vec2<u32>',
  55518. bvec2: 'vec2<bool>',
  55519. vec3: 'vec3<f32>',
  55520. ivec3: 'vec3<i32>',
  55521. uvec3: 'vec3<u32>',
  55522. bvec3: 'vec3<bool>',
  55523. vec4: 'vec4<f32>',
  55524. ivec4: 'vec4<i32>',
  55525. uvec4: 'vec4<u32>',
  55526. bvec4: 'vec4<bool>',
  55527. mat2: 'mat2x2<f32>',
  55528. mat3: 'mat3x3<f32>',
  55529. mat4: 'mat4x4<f32>'
  55530. };
  55531. const wgslCodeCache = {};
  55532. const wgslPolyfill = {
  55533. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  55534. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  55535. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  55536. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  55537. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  55538. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  55539. 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 ); }' ),
  55540. 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 ); }' ),
  55541. 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 ); }' ),
  55542. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  55543. 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 ); }' ),
  55544. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  55545. inverse_mat2: new CodeNode( /* wgsl */`
  55546. fn tsl_inverse_mat2( m : mat2x2<f32> ) -> mat2x2<f32> {
  55547. let det = m[ 0 ][ 0 ] * m[ 1 ][ 1 ] - m[ 0 ][ 1 ] * m[ 1 ][ 0 ];
  55548. return mat2x2<f32>(
  55549. m[ 1 ][ 1 ], - m[ 0 ][ 1 ],
  55550. - m[ 1 ][ 0 ], m[ 0 ][ 0 ]
  55551. ) * ( 1.0 / det );
  55552. }
  55553. ` ),
  55554. inverse_mat3: new CodeNode( /* wgsl */`
  55555. fn tsl_inverse_mat3( m : mat3x3<f32> ) -> mat3x3<f32> {
  55556. let a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ];
  55557. let a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ];
  55558. let a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ];
  55559. let b01 = a22 * a11 - a12 * a21;
  55560. let b11 = - a22 * a10 + a12 * a20;
  55561. let b21 = a21 * a10 - a11 * a20;
  55562. let det = a00 * b01 + a01 * b11 + a02 * b21;
  55563. return mat3x3<f32>(
  55564. b01, ( - a22 * a01 + a02 * a21 ), ( a12 * a01 - a02 * a11 ),
  55565. b11, ( a22 * a00 - a02 * a20 ), ( - a12 * a00 + a02 * a10 ),
  55566. b21, ( - a21 * a00 + a01 * a20 ), ( a11 * a00 - a01 * a10 )
  55567. ) * ( 1.0 / det );
  55568. }
  55569. ` ),
  55570. inverse_mat4: new CodeNode( /* wgsl */`
  55571. fn tsl_inverse_mat4( m : mat4x4<f32> ) -> mat4x4<f32> {
  55572. let a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ]; let a03 = m[ 0 ][ 3 ];
  55573. let a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ]; let a13 = m[ 1 ][ 3 ];
  55574. let a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ]; let a23 = m[ 2 ][ 3 ];
  55575. let a30 = m[ 3 ][ 0 ]; let a31 = m[ 3 ][ 1 ]; let a32 = m[ 3 ][ 2 ]; let a33 = m[ 3 ][ 3 ];
  55576. let b00 = a00 * a11 - a01 * a10;
  55577. let b01 = a00 * a12 - a02 * a10;
  55578. let b02 = a00 * a13 - a03 * a10;
  55579. let b03 = a01 * a12 - a02 * a11;
  55580. let b04 = a01 * a13 - a03 * a11;
  55581. let b05 = a02 * a13 - a03 * a12;
  55582. let b06 = a20 * a31 - a21 * a30;
  55583. let b07 = a20 * a32 - a22 * a30;
  55584. let b08 = a20 * a33 - a23 * a30;
  55585. let b09 = a21 * a32 - a22 * a31;
  55586. let b10 = a21 * a33 - a23 * a31;
  55587. let b11 = a22 * a33 - a23 * a32;
  55588. let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  55589. return mat4x4<f32>(
  55590. a11 * b11 - a12 * b10 + a13 * b09,
  55591. a02 * b10 - a01 * b11 - a03 * b09,
  55592. a31 * b05 - a32 * b04 + a33 * b03,
  55593. a22 * b04 - a21 * b05 - a23 * b03,
  55594. a12 * b08 - a10 * b11 - a13 * b07,
  55595. a00 * b11 - a02 * b08 + a03 * b07,
  55596. a32 * b02 - a30 * b05 - a33 * b01,
  55597. a20 * b05 - a22 * b02 + a23 * b01,
  55598. a10 * b10 - a11 * b08 + a13 * b06,
  55599. a01 * b08 - a00 * b10 - a03 * b06,
  55600. a30 * b04 - a31 * b02 + a33 * b00,
  55601. a21 * b02 - a20 * b04 - a23 * b00,
  55602. a11 * b07 - a10 * b09 - a12 * b06,
  55603. a00 * b09 - a01 * b07 + a02 * b06,
  55604. a31 * b01 - a30 * b03 - a32 * b00,
  55605. a20 * b03 - a21 * b01 + a22 * b00
  55606. ) * ( 1.0 / det );
  55607. }
  55608. ` ),
  55609. biquadraticTexture: new CodeNode( /* wgsl */`
  55610. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  55611. let res = vec2f( iRes );
  55612. let uvScaled = coord * res;
  55613. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  55614. // https://www.shadertoy.com/view/WtyXRy
  55615. let uv = uvWrapping - 0.5;
  55616. let iuv = floor( uv );
  55617. let f = fract( uv );
  55618. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  55619. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  55620. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  55621. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  55622. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  55623. }
  55624. ` ),
  55625. biquadraticTextureArray: new CodeNode( /* wgsl */`
  55626. fn tsl_biquadraticTexture_array( map : texture_2d_array<f32>, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {
  55627. let res = vec2f( iRes );
  55628. let uvScaled = coord * res;
  55629. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  55630. // https://www.shadertoy.com/view/WtyXRy
  55631. let uv = uvWrapping - 0.5;
  55632. let iuv = floor( uv );
  55633. let f = fract( uv );
  55634. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );
  55635. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );
  55636. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );
  55637. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );
  55638. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  55639. }
  55640. ` )
  55641. };
  55642. const wgslMethods = {
  55643. dFdx: 'dpdx',
  55644. dFdy: '- dpdy',
  55645. mod_float: 'tsl_mod_float',
  55646. mod_vec2: 'tsl_mod_vec2',
  55647. mod_vec3: 'tsl_mod_vec3',
  55648. mod_vec4: 'tsl_mod_vec4',
  55649. equals_bool: 'tsl_equals_bool',
  55650. equals_bvec2: 'tsl_equals_bvec2',
  55651. equals_bvec3: 'tsl_equals_bvec3',
  55652. equals_bvec4: 'tsl_equals_bvec4',
  55653. inverse_mat2: 'tsl_inverse_mat2',
  55654. inverse_mat3: 'tsl_inverse_mat3',
  55655. inverse_mat4: 'tsl_inverse_mat4',
  55656. inversesqrt: 'inverseSqrt',
  55657. bitcast: 'bitcast<f32>',
  55658. floatpack_snorm_2x16: 'pack2x16snorm',
  55659. floatpack_unorm_2x16: 'pack2x16unorm',
  55660. floatpack_float16_2x16: 'pack2x16float',
  55661. floatunpack_snorm_2x16: 'unpack2x16snorm',
  55662. floatunpack_unorm_2x16: 'unpack2x16unorm',
  55663. floatunpack_float16_2x16: 'unpack2x16float'
  55664. };
  55665. //
  55666. let diagnostics = '';
  55667. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  55668. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  55669. }
  55670. /**
  55671. * A node builder targeting WGSL.
  55672. *
  55673. * This module generates WGSL shader code from node materials and also
  55674. * generates the respective bindings and vertex buffer definitions. These
  55675. * data are later used by the renderer to create render and compute pipelines
  55676. * for render objects.
  55677. *
  55678. * @augments NodeBuilder
  55679. */
  55680. class WGSLNodeBuilder extends NodeBuilder {
  55681. /**
  55682. * Constructs a new WGSL node builder renderer.
  55683. *
  55684. * @param {Object3D} object - The 3D object.
  55685. * @param {Renderer} renderer - The renderer.
  55686. */
  55687. constructor( object, renderer ) {
  55688. super( object, renderer, new WGSLNodeParser() );
  55689. /**
  55690. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  55691. * another dictionary which manages UBOs per group ('render','frame','object').
  55692. *
  55693. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  55694. */
  55695. this.uniformGroups = {};
  55696. /**
  55697. * A dictionary that holds the assigned binding indices for each uniform group.
  55698. * This ensures the same binding index is used across all shader stages.
  55699. *
  55700. * @type {Object<string,{index: number, id: number}>}
  55701. */
  55702. this.uniformGroupsBindings = {};
  55703. /**
  55704. * A dictionary that holds for each shader stage a Map of builtins.
  55705. *
  55706. * @type {Object<string,Map<string,Object>>}
  55707. */
  55708. this.builtins = {};
  55709. /**
  55710. * A dictionary that holds for each shader stage a Set of directives.
  55711. *
  55712. * @type {Object<string,Set<string>>}
  55713. */
  55714. this.directives = {};
  55715. /**
  55716. * A map for managing scope arrays. Only relevant for when using
  55717. * {@link WorkgroupInfoNode} in context of compute shaders.
  55718. *
  55719. * @type {Map<string,Object>}
  55720. */
  55721. this.scopedArrays = new Map();
  55722. /**
  55723. * A flag that indicates that early returns are allowed.
  55724. *
  55725. * @type {boolean}
  55726. * @default true
  55727. */
  55728. this.allowEarlyReturns = true;
  55729. /**
  55730. * A flag that indicates that global variables are allowed.
  55731. *
  55732. * @type {boolean}
  55733. * @default true
  55734. */
  55735. this.allowGlobalVariables = true;
  55736. }
  55737. /**
  55738. * Generates the WGSL snippet for sampled textures.
  55739. *
  55740. * @private
  55741. * @param {Texture} texture - The texture.
  55742. * @param {string} textureProperty - The name of the texture uniform in the shader.
  55743. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  55744. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  55745. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  55746. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  55747. * @return {string} The WGSL snippet.
  55748. */
  55749. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  55750. if ( shaderStage === 'fragment' ) {
  55751. if ( depthSnippet ) {
  55752. if ( offsetSnippet ) {
  55753. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  55754. }
  55755. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  55756. } else {
  55757. if ( offsetSnippet ) {
  55758. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  55759. }
  55760. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  55761. }
  55762. } else {
  55763. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  55764. }
  55765. }
  55766. /**
  55767. * Generates the WGSL snippet when sampling textures with explicit mip level.
  55768. *
  55769. * @private
  55770. * @param {Texture} texture - The texture.
  55771. * @param {string} textureProperty - The name of the texture uniform in the shader.
  55772. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  55773. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  55774. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  55775. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  55776. * @return {string} The WGSL snippet.
  55777. */
  55778. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  55779. if ( this.isUnfilterable( texture ) === false ) {
  55780. if ( depthSnippet ) {
  55781. if ( offsetSnippet ) {
  55782. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  55783. }
  55784. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  55785. } else {
  55786. if ( offsetSnippet ) {
  55787. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  55788. }
  55789. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  55790. }
  55791. } else if ( this.isFilteredTexture( texture ) ) {
  55792. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet, depthSnippet );
  55793. } else {
  55794. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  55795. }
  55796. }
  55797. /**
  55798. * Generates a wrap function used in context of textures.
  55799. *
  55800. * @param {Texture} texture - The texture to generate the function for.
  55801. * @return {string} The name of the generated function.
  55802. */
  55803. generateWrapFunction( texture ) {
  55804. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }T_${ texture.is3DTexture || texture.isData3DTexture ? '3d' : '2d' }`;
  55805. let nodeCode = wgslCodeCache[ functionName ];
  55806. if ( nodeCode === undefined ) {
  55807. const includes = [];
  55808. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  55809. const coordType = texture.is3DTexture || texture.isData3DTexture ? 'vec3f' : 'vec2f';
  55810. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  55811. const addWrapSnippet = ( wrap, axis ) => {
  55812. if ( wrap === RepeatWrapping ) {
  55813. includes.push( wgslPolyfill.repeatWrapping_float );
  55814. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  55815. } else if ( wrap === ClampToEdgeWrapping ) {
  55816. includes.push( wgslPolyfill.clampWrapping_float );
  55817. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  55818. } else if ( wrap === MirroredRepeatWrapping ) {
  55819. includes.push( wgslPolyfill.mirrorWrapping_float );
  55820. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  55821. } else {
  55822. code += `\t\tcoord.${ axis }`;
  55823. warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  55824. }
  55825. };
  55826. addWrapSnippet( texture.wrapS, 'x' );
  55827. code += ',\n';
  55828. addWrapSnippet( texture.wrapT, 'y' );
  55829. if ( texture.is3DTexture || texture.isData3DTexture ) {
  55830. code += ',\n';
  55831. addWrapSnippet( texture.wrapR, 'z' );
  55832. }
  55833. code += '\n\t);\n\n}\n';
  55834. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  55835. }
  55836. nodeCode.build( this );
  55837. return functionName;
  55838. }
  55839. /**
  55840. * Generates the array declaration string.
  55841. *
  55842. * @param {string} type - The type.
  55843. * @param {?number} [count] - The count.
  55844. * @return {string} The generated value as a shader string.
  55845. */
  55846. generateArrayDeclaration( type, count ) {
  55847. return `array< ${ this.getType( type ) }, ${ count } >`;
  55848. }
  55849. /**
  55850. * Generates a WGSL variable that holds the texture dimension of the given texture.
  55851. * It also returns information about the number of layers (elements) of an arrayed
  55852. * texture as well as the cube face count of cube textures.
  55853. *
  55854. * @param {Texture} texture - The texture to generate the function for.
  55855. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  55856. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  55857. * @return {string} The name of the dimension variable.
  55858. */
  55859. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  55860. const textureData = this.getDataFromNode( texture, this.shaderStage, this.cache );
  55861. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  55862. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  55863. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  55864. let textureDimensionsParams;
  55865. let dimensionType;
  55866. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  55867. const isMultisampled = primarySamples > 1;
  55868. if ( texture.is3DTexture || texture.isData3DTexture ) {
  55869. dimensionType = 'vec3<u32>';
  55870. } else {
  55871. // Regular 2D textures, depth textures, etc.
  55872. dimensionType = 'vec2<u32>';
  55873. }
  55874. // Build parameters string based on texture type and multisampling
  55875. if ( isMultisampled || texture.isStorageTexture ) {
  55876. textureDimensionsParams = textureProperty;
  55877. } else {
  55878. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  55879. }
  55880. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  55881. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  55882. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.is3DTexture || texture.isData3DTexture ) {
  55883. textureData.arrayLayerCount = new VarNode(
  55884. new ExpressionNode(
  55885. `textureNumLayers(${textureProperty})`,
  55886. 'u32'
  55887. )
  55888. );
  55889. }
  55890. // For cube textures, we know it's always 6 faces
  55891. if ( texture.isTextureCube ) {
  55892. textureData.cubeFaceCount = new VarNode(
  55893. new ExpressionNode( '6u', 'u32' )
  55894. );
  55895. }
  55896. }
  55897. return textureDimensionNode.build( this );
  55898. }
  55899. /**
  55900. * Generates the WGSL snippet for a manual filtered texture.
  55901. *
  55902. * @param {Texture} texture - The texture.
  55903. * @param {string} textureProperty - The name of the texture uniform in the shader.
  55904. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  55905. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  55906. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  55907. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  55908. * @return {string} The WGSL snippet.
  55909. */
  55910. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u', depthSnippet ) {
  55911. const wrapFunction = this.generateWrapFunction( texture );
  55912. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  55913. if ( offsetSnippet ) {
  55914. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  55915. }
  55916. if ( depthSnippet ) {
  55917. this._include( 'biquadraticTextureArray' );
  55918. return `tsl_biquadraticTexture_array( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ depthSnippet } ), u32( ${ levelSnippet } ) )`;
  55919. }
  55920. this._include( 'biquadraticTexture' );
  55921. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  55922. }
  55923. /**
  55924. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  55925. * Since it's a lookup, no sampling or filtering is applied.
  55926. *
  55927. * @param {Texture} texture - The texture.
  55928. * @param {string} textureProperty - The name of the texture uniform in the shader.
  55929. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  55930. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  55931. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  55932. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  55933. * @return {string} The WGSL snippet.
  55934. */
  55935. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  55936. // Cube textures cannot use textureLoad in WGSL, must use textureSampleLevel
  55937. if ( texture.isCubeTexture === true ) {
  55938. if ( offsetSnippet ) {
  55939. uvSnippet = `${ uvSnippet } + vec3<f32>(${ offsetSnippet })`;
  55940. }
  55941. // Depth textures require integer level, regular textures use float
  55942. const levelType = texture.isDepthTexture ? 'u32' : 'f32';
  55943. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelType }( ${ levelSnippet } ) )`;
  55944. }
  55945. const wrapFunction = this.generateWrapFunction( texture );
  55946. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  55947. const vecType = texture.is3DTexture || texture.isData3DTexture ? 'vec3' : 'vec2';
  55948. const textureDimensionMargin = ( vecType === 'vec3' ) ? 'vec3<u32>( 1, 1, 1 )' : 'vec2<u32>( 1, 1 )';
  55949. if ( offsetSnippet ) {
  55950. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  55951. }
  55952. const clampMin = `${ vecType }<f32>( 0 )`;
  55953. const clampMax = `${ vecType }<f32>( ${ textureDimension } - ${ textureDimensionMargin } )`;
  55954. uvSnippet = `${ vecType }<u32>( clamp( floor( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) ), ${ clampMin }, ${ clampMax } ) )`;
  55955. return this.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, null );
  55956. }
  55957. /**
  55958. * Generates the WGSL snippet that reads a single texel from a storage texture.
  55959. *
  55960. * @param {Texture} texture - The texture.
  55961. * @param {string} textureProperty - The name of the texture uniform in the shader.
  55962. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  55963. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  55964. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  55965. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  55966. * @return {string} The WGSL snippet.
  55967. */
  55968. generateStorageTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  55969. if ( offsetSnippet ) {
  55970. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  55971. }
  55972. let snippet;
  55973. if ( depthSnippet ) {
  55974. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet } )`;
  55975. } else {
  55976. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  55977. }
  55978. return snippet;
  55979. }
  55980. /**
  55981. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  55982. *
  55983. * @param {Texture} texture - The texture.
  55984. * @param {string} textureProperty - The name of the texture uniform in the shader.
  55985. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  55986. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  55987. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  55988. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  55989. * @return {string} The WGSL snippet.
  55990. */
  55991. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  55992. if ( levelSnippet === null ) levelSnippet = '0u';
  55993. if ( offsetSnippet ) {
  55994. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  55995. }
  55996. let snippet;
  55997. if ( depthSnippet ) {
  55998. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  55999. } else {
  56000. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  56001. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  56002. snippet += '.x';
  56003. }
  56004. }
  56005. return snippet;
  56006. }
  56007. /**
  56008. * Generates the WGSL snippet that writes a single texel to a texture.
  56009. *
  56010. * @param {Texture} texture - The texture.
  56011. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56012. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56013. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56014. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  56015. * @return {string} The WGSL snippet.
  56016. */
  56017. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  56018. let snippet;
  56019. if ( depthSnippet ) {
  56020. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  56021. } else {
  56022. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  56023. }
  56024. return snippet;
  56025. }
  56026. /**
  56027. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  56028. *
  56029. * @param {Texture} texture - The texture.
  56030. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  56031. */
  56032. isSampleCompare( texture ) {
  56033. return texture.isDepthTexture === true && texture.compareFunction !== null && this.renderer.hasCompatibility( Compatibility.TEXTURE_COMPARE );
  56034. }
  56035. /**
  56036. * Returns `true` if the given texture is unfilterable.
  56037. *
  56038. * @param {Texture} texture - The texture.
  56039. * @return {boolean} Whether the given texture is unfilterable or not.
  56040. */
  56041. isUnfilterable( texture ) {
  56042. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  56043. ( ! this.isAvailable( 'float32Filterable' ) && texture.type === FloatType ) ||
  56044. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  56045. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  56046. }
  56047. /**
  56048. * Generates the WGSL snippet for sampling/loading the given texture.
  56049. *
  56050. * @param {Texture} texture - The texture.
  56051. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56052. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56053. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56054. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56055. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  56056. * @return {string} The WGSL snippet.
  56057. */
  56058. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  56059. let snippet = null;
  56060. if ( this.isUnfilterable( texture ) ) {
  56061. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  56062. } else {
  56063. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  56064. }
  56065. return snippet;
  56066. }
  56067. /**
  56068. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  56069. *
  56070. * @param {Texture} texture - The texture.
  56071. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56072. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56073. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  56074. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56075. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56076. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  56077. * @return {string} The WGSL snippet.
  56078. */
  56079. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  56080. if ( shaderStage === 'fragment' ) {
  56081. if ( depthSnippet ) {
  56082. if ( offsetSnippet ) {
  56083. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  56084. }
  56085. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  56086. } else {
  56087. if ( offsetSnippet ) {
  56088. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  56089. }
  56090. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  56091. }
  56092. } else {
  56093. error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  56094. }
  56095. }
  56096. /**
  56097. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  56098. * against a reference value.
  56099. *
  56100. * @param {Texture} texture - The texture.
  56101. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56102. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56103. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  56104. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56105. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56106. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  56107. * @return {string} The WGSL snippet.
  56108. */
  56109. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  56110. if ( shaderStage === 'fragment' ) {
  56111. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  56112. if ( offsetSnippet ) {
  56113. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  56114. }
  56115. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  56116. }
  56117. if ( offsetSnippet ) {
  56118. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  56119. }
  56120. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  56121. } else {
  56122. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  56123. }
  56124. }
  56125. /**
  56126. * Generates the WGSL snippet for gathering four texels from the given texture.
  56127. *
  56128. * @param {Texture} texture - The texture.
  56129. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56130. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56131. * @param {string} gatherSnippet - A WGSL snippet that represents the index of the channel to read.
  56132. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56133. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56134. * @param {?string} flipYSnippet - A WGSL snippet that represents the y-flip. Only used for WebGL.
  56135. * @return {string} The WGSL snippet.
  56136. */
  56137. generateTextureGather( texture, textureProperty, uvSnippet, gatherSnippet, depthSnippet, offsetSnippet ) {
  56138. const componentSnippet = texture.isDepthTexture === true ? '' : `${gatherSnippet}, `;
  56139. if ( depthSnippet ) {
  56140. if ( offsetSnippet ) {
  56141. return `textureGather( ${componentSnippet}${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  56142. }
  56143. return `textureGather( ${componentSnippet}${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  56144. }
  56145. if ( offsetSnippet ) {
  56146. return `textureGather( ${componentSnippet}${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  56147. }
  56148. return `textureGather( ${componentSnippet}${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet })`;
  56149. }
  56150. /**
  56151. * Generates the WGSL snippet for performing a depth comparison on four texels in the given depth texture.
  56152. *
  56153. * @param {Texture} texture - The texture.
  56154. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56155. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56156. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  56157. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56158. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56159. * @param {?string} flipYSnippet - A WGSL snippet that represents the y-flip. Only used for WebGL.
  56160. * @return {string} The WGSL snippet.
  56161. */
  56162. generateTextureGatherCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet ) {
  56163. if ( depthSnippet ) {
  56164. if ( offsetSnippet ) {
  56165. return `textureGatherCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  56166. }
  56167. return `textureGatherCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet })`;
  56168. }
  56169. if ( offsetSnippet ) {
  56170. return `textureGatherCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  56171. }
  56172. return `textureGatherCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet })`;
  56173. }
  56174. /**
  56175. * Generates the WGSL snippet when sampling textures with explicit mip level.
  56176. *
  56177. * @param {Texture} texture - The texture.
  56178. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56179. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56180. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  56181. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56182. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56183. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  56184. * @return {string} The WGSL snippet.
  56185. */
  56186. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  56187. if ( this.isUnfilterable( texture ) === false ) {
  56188. if ( depthSnippet ) {
  56189. if ( offsetSnippet ) {
  56190. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  56191. }
  56192. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  56193. } else {
  56194. if ( offsetSnippet ) {
  56195. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  56196. }
  56197. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  56198. }
  56199. } else if ( this.isFilteredTexture( texture ) ) {
  56200. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet, depthSnippet );
  56201. } else {
  56202. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  56203. }
  56204. }
  56205. /**
  56206. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  56207. *
  56208. * @param {Texture} texture - The texture.
  56209. * @param {string} textureProperty - The name of the texture uniform in the shader.
  56210. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  56211. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  56212. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  56213. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  56214. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  56215. * @return {string} The WGSL snippet.
  56216. */
  56217. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  56218. if ( shaderStage === 'fragment' ) {
  56219. if ( depthSnippet ) {
  56220. if ( offsetSnippet ) {
  56221. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  56222. }
  56223. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ biasSnippet } )`;
  56224. } else {
  56225. if ( offsetSnippet ) {
  56226. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  56227. }
  56228. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  56229. }
  56230. } else {
  56231. error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  56232. }
  56233. }
  56234. /**
  56235. * Returns a WGSL snippet that represents the property name of the given node.
  56236. *
  56237. * @param {Node} node - The node.
  56238. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  56239. * @return {string} The property name.
  56240. */
  56241. getPropertyName( node, shaderStage = this.shaderStage ) {
  56242. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  56243. if ( shaderStage === 'vertex' ) {
  56244. return `varyings.${ node.name }`;
  56245. }
  56246. } else if ( node.isNodeUniform === true ) {
  56247. const name = node.name;
  56248. const type = node.type;
  56249. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  56250. return name;
  56251. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  56252. if ( this.isCustomStruct( node ) ) {
  56253. return name;
  56254. }
  56255. return name + '.value';
  56256. } else {
  56257. return node.groupNode.name + '.' + name;
  56258. }
  56259. }
  56260. return super.getPropertyName( node );
  56261. }
  56262. /**
  56263. * Returns the output struct name.
  56264. *
  56265. * @return {string} The name of the output struct.
  56266. */
  56267. getOutputStructName() {
  56268. return 'output';
  56269. }
  56270. /**
  56271. * Returns the native shader operator name for a given generic name.
  56272. *
  56273. * @param {string} op - The operator name to resolve.
  56274. * @return {?string} The resolved operator name.
  56275. */
  56276. getFunctionOperator( op ) {
  56277. const fnOp = wgslFnOpLib[ op ];
  56278. if ( fnOp !== undefined ) {
  56279. this._include( fnOp );
  56280. return fnOp;
  56281. }
  56282. return null;
  56283. }
  56284. /**
  56285. * Returns the node access for the given node and shader stage.
  56286. *
  56287. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  56288. * @param {string} shaderStage - The shader stage.
  56289. * @return {string} The node access.
  56290. */
  56291. getNodeAccess( node, shaderStage ) {
  56292. if ( shaderStage !== 'compute' ) {
  56293. if ( node.isAtomic === true ) {
  56294. warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  56295. return NodeAccess.READ_WRITE;
  56296. }
  56297. return NodeAccess.READ_ONLY;
  56298. }
  56299. return node.access;
  56300. }
  56301. /**
  56302. * Returns A WGSL snippet representing the storage access.
  56303. *
  56304. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  56305. * @param {string} shaderStage - The shader stage.
  56306. * @return {string} The WGSL snippet representing the storage access.
  56307. */
  56308. getStorageAccess( node, shaderStage ) {
  56309. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  56310. }
  56311. /**
  56312. * This method is one of the more important ones since it's responsible
  56313. * for generating a matching binding instance for the given uniform node.
  56314. *
  56315. * These bindings are later used in the renderer to create bind groups
  56316. * and layouts.
  56317. *
  56318. * @param {UniformNode} node - The uniform node.
  56319. * @param {string} type - The node data type.
  56320. * @param {string} shaderStage - The shader stage.
  56321. * @param {?string} [name=null] - An optional uniform name.
  56322. * @return {NodeUniform} The node uniform object.
  56323. */
  56324. getUniformFromNode( node, type, shaderStage, name = null ) {
  56325. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  56326. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  56327. if ( nodeData.uniformGPU === undefined ) {
  56328. let uniformGPU;
  56329. const group = node.groupNode;
  56330. const groupName = group.name;
  56331. const bindings = this.getBindGroupArray( groupName, shaderStage );
  56332. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  56333. let texture = null;
  56334. const access = this.getNodeAccess( node, shaderStage );
  56335. if ( type === 'texture' || type === 'storageTexture' ) {
  56336. if ( node.value.is3DTexture === true ) {
  56337. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  56338. } else {
  56339. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  56340. }
  56341. } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
  56342. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  56343. } else if ( type === 'texture3D' ) {
  56344. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  56345. }
  56346. texture.store = node.isStorageTextureNode === true;
  56347. texture.mipLevel = texture.store ? node.mipLevel : 0;
  56348. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  56349. // Cube textures always need samplers (they use textureSampleLevel, not textureLoad)
  56350. // Also textureGather always need sampler.
  56351. const needsSampler = node.value.isCubeTexture === true || ( this.isUnfilterable( node.value ) === false && texture.store === false ) || node.gatherNode !== null;
  56352. if ( needsSampler ) {
  56353. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  56354. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  56355. bindings.push( sampler, texture );
  56356. uniformGPU = [ sampler, texture ];
  56357. } else {
  56358. bindings.push( texture );
  56359. uniformGPU = [ texture ];
  56360. }
  56361. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  56362. const sharedData = this.getSharedDataFromNode( node );
  56363. let buffer = sharedData.buffer;
  56364. if ( buffer === undefined ) {
  56365. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  56366. buffer = new bufferClass( node, group );
  56367. sharedData.buffer = buffer;
  56368. }
  56369. buffer.setVisibility( buffer.getVisibility() | gpuShaderStageLib[ shaderStage ] );
  56370. bindings.push( buffer );
  56371. uniformGPU = buffer;
  56372. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  56373. } else {
  56374. let uniformsGroup = this.uniformGroups[ groupName ];
  56375. if ( uniformsGroup === undefined ) {
  56376. uniformsGroup = new NodeUniformsGroup( groupName, group );
  56377. uniformsGroup.setVisibility( GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT | GPUShaderStage.COMPUTE );
  56378. this.uniformGroups[ groupName ] = uniformsGroup;
  56379. }
  56380. // Add to bindings for this stage if not already present
  56381. if ( bindings.indexOf( uniformsGroup ) === -1 ) {
  56382. bindings.push( uniformsGroup );
  56383. }
  56384. uniformGPU = this.getNodeUniform( uniformNode, type );
  56385. // Only add uniform if not already present in the group (check by name to avoid duplicates across stages)
  56386. const uniformName = uniformGPU.name;
  56387. const alreadyExists = uniformsGroup.uniforms.some( u => u.name === uniformName );
  56388. if ( ! alreadyExists ) {
  56389. uniformsGroup.addUniform( uniformGPU );
  56390. }
  56391. }
  56392. nodeData.uniformGPU = uniformGPU;
  56393. }
  56394. return uniformNode;
  56395. }
  56396. /**
  56397. * This method should be used whenever builtins are required in nodes.
  56398. * The internal builtins data structure will make sure builtins are
  56399. * defined in the WGSL source.
  56400. *
  56401. * @param {string} name - The builtin name.
  56402. * @param {string} property - The property name.
  56403. * @param {string} type - The node data type.
  56404. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  56405. * @return {string} The property name.
  56406. */
  56407. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  56408. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  56409. if ( map.has( name ) === false ) {
  56410. map.set( name, {
  56411. name,
  56412. property,
  56413. type
  56414. } );
  56415. }
  56416. return property;
  56417. }
  56418. /**
  56419. * Returns `true` if the given builtin is defined in the given shader stage.
  56420. *
  56421. * @param {string} name - The builtin name.
  56422. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  56423. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  56424. */
  56425. hasBuiltin( name, shaderStage = this.shaderStage ) {
  56426. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  56427. }
  56428. /**
  56429. * Returns the vertex index builtin.
  56430. *
  56431. * @return {string} The vertex index.
  56432. */
  56433. getVertexIndex() {
  56434. if ( this.shaderStage === 'vertex' ) {
  56435. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  56436. }
  56437. return 'vertexIndex';
  56438. }
  56439. /**
  56440. * Builds the given shader node.
  56441. *
  56442. * @param {ShaderNodeInternal} shaderNode - The shader node.
  56443. * @return {string} The WGSL function code.
  56444. */
  56445. buildFunctionCode( shaderNode ) {
  56446. const layout = shaderNode.layout;
  56447. const flowData = this.flowShaderNode( shaderNode );
  56448. const parameters = [];
  56449. for ( const input of layout.inputs ) {
  56450. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  56451. }
  56452. //
  56453. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  56454. ${ flowData.vars }
  56455. ${ flowData.code }
  56456. `;
  56457. if ( flowData.result ) {
  56458. code += `\treturn ${ flowData.result };\n`;
  56459. }
  56460. code += '\n}\n';
  56461. //
  56462. return code;
  56463. }
  56464. /**
  56465. * Contextually returns either the vertex stage instance index builtin
  56466. * or the linearized index of an compute invocation within a grid of workgroups.
  56467. *
  56468. * @return {string} The instance index.
  56469. */
  56470. getInstanceIndex() {
  56471. if ( this.shaderStage === 'vertex' ) {
  56472. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  56473. }
  56474. return 'instanceIndex';
  56475. }
  56476. /**
  56477. * Returns a builtin representing the index of a compute invocation within the scope of a workgroup load.
  56478. *
  56479. * @return {string} The invocation local index.
  56480. */
  56481. getInvocationLocalIndex() {
  56482. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  56483. }
  56484. /**
  56485. * Returns a builtin representing the size of a subgroup within the current shader.
  56486. *
  56487. * @return {string} The subgroup size.
  56488. */
  56489. getSubgroupSize() {
  56490. this.enableSubGroups();
  56491. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  56492. }
  56493. /**
  56494. * Returns a builtin representing the index of a compute invocation within the scope of a subgroup.
  56495. *
  56496. * @return {string} The invocation subgroup index.
  56497. */
  56498. getInvocationSubgroupIndex() {
  56499. this.enableSubGroups();
  56500. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  56501. }
  56502. /**
  56503. * Returns a builtin representing the index of a compute invocation's subgroup within its workgroup.
  56504. *
  56505. * @return {string} The subgroup index.
  56506. */
  56507. getSubgroupIndex() {
  56508. this.enableSubGroups();
  56509. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  56510. }
  56511. /**
  56512. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  56513. *
  56514. * @return {null} Null.
  56515. */
  56516. getDrawIndex() {
  56517. return null;
  56518. }
  56519. /**
  56520. * Returns the front facing builtin.
  56521. *
  56522. * @return {string} The front facing builtin.
  56523. */
  56524. getFrontFacing() {
  56525. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  56526. }
  56527. /**
  56528. * Returns the frag coord builtin.
  56529. *
  56530. * @return {string} The frag coord builtin.
  56531. */
  56532. getFragCoord() {
  56533. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  56534. }
  56535. /**
  56536. * Returns the frag depth builtin.
  56537. *
  56538. * @return {string} The frag depth builtin.
  56539. */
  56540. getFragDepth() {
  56541. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  56542. }
  56543. /**
  56544. * Returns the clip distances builtin.
  56545. *
  56546. * @return {string} The clip distances builtin.
  56547. */
  56548. getClipDistance() {
  56549. return 'varyings.hw_clip_distances';
  56550. }
  56551. /**
  56552. * Whether to flip texture data along its vertical axis or not.
  56553. *
  56554. * @return {boolean} Returns always `false` in context of WGSL.
  56555. */
  56556. isFlipY() {
  56557. return false;
  56558. }
  56559. /**
  56560. * Enables the given directive for the given shader stage.
  56561. *
  56562. * @param {string} name - The directive name.
  56563. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  56564. */
  56565. enableDirective( name, shaderStage = this.shaderStage ) {
  56566. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  56567. stage.add( name );
  56568. }
  56569. /**
  56570. * Returns the directives of the given shader stage as a WGSL string.
  56571. *
  56572. * @param {string} shaderStage - The shader stage.
  56573. * @return {string} A WGSL snippet that enables the directives of the given stage.
  56574. */
  56575. getDirectives( shaderStage ) {
  56576. const snippets = [];
  56577. const directives = this.directives[ shaderStage ];
  56578. if ( directives !== undefined ) {
  56579. for ( const directive of directives ) {
  56580. snippets.push( `enable ${directive};` );
  56581. }
  56582. }
  56583. return snippets.join( '\n' );
  56584. }
  56585. /**
  56586. * Enables the 'subgroups' directive.
  56587. */
  56588. enableSubGroups() {
  56589. this.enableDirective( 'subgroups' );
  56590. }
  56591. /**
  56592. * Enables the 'subgroups-f16' directive.
  56593. */
  56594. enableSubgroupsF16() {
  56595. this.enableDirective( 'subgroups-f16' );
  56596. }
  56597. /**
  56598. * Enables the 'clip_distances' directive.
  56599. */
  56600. enableClipDistances() {
  56601. this.enableDirective( 'clip_distances' );
  56602. }
  56603. /**
  56604. * Enables the 'f16' directive.
  56605. */
  56606. enableShaderF16() {
  56607. this.enableDirective( 'f16' );
  56608. }
  56609. /**
  56610. * Enables the 'dual_source_blending' directive.
  56611. */
  56612. enableDualSourceBlending() {
  56613. this.enableDirective( 'dual_source_blending' );
  56614. }
  56615. /**
  56616. * Enables hardware clipping.
  56617. *
  56618. * @param {string} planeCount - The clipping plane count.
  56619. */
  56620. enableHardwareClipping( planeCount ) {
  56621. this.enableClipDistances();
  56622. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  56623. }
  56624. /**
  56625. * Returns the builtins of the given shader stage as a WGSL string.
  56626. *
  56627. * @param {string} shaderStage - The shader stage.
  56628. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  56629. */
  56630. getBuiltins( shaderStage ) {
  56631. const snippets = [];
  56632. const builtins = this.builtins[ shaderStage ];
  56633. if ( builtins !== undefined ) {
  56634. for ( const { name, property, type } of builtins.values() ) {
  56635. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  56636. }
  56637. }
  56638. return snippets.join( ',\n\t' );
  56639. }
  56640. /**
  56641. * This method should be used when a new scoped buffer is used in context of
  56642. * compute shaders. It adds the array to the internal data structure which is
  56643. * later used to generate the respective WGSL.
  56644. *
  56645. * @param {string} name - The array name.
  56646. * @param {string} scope - The scope.
  56647. * @param {string} bufferType - The buffer type.
  56648. * @param {string} bufferCount - The buffer count.
  56649. * @return {string} The array name.
  56650. */
  56651. getScopedArray( name, scope, bufferType, bufferCount ) {
  56652. if ( this.scopedArrays.has( name ) === false ) {
  56653. this.scopedArrays.set( name, {
  56654. name,
  56655. scope,
  56656. bufferType,
  56657. bufferCount
  56658. } );
  56659. }
  56660. return name;
  56661. }
  56662. /**
  56663. * Returns the scoped arrays of the given shader stage as a WGSL string.
  56664. *
  56665. * @param {string} shaderStage - The shader stage.
  56666. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  56667. * Returns `undefined` when used in the vertex or fragment stage.
  56668. */
  56669. getScopedArrays( shaderStage ) {
  56670. if ( shaderStage !== 'compute' ) {
  56671. return;
  56672. }
  56673. const snippets = [];
  56674. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  56675. const type = this.getType( bufferType );
  56676. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  56677. }
  56678. return snippets.join( '\n' );
  56679. }
  56680. /**
  56681. * Returns the shader attributes of the given shader stage as a WGSL string.
  56682. *
  56683. * @param {string} shaderStage - The shader stage.
  56684. * @return {string} The WGSL snippet that defines the shader attributes.
  56685. */
  56686. getAttributes( shaderStage ) {
  56687. const snippets = [];
  56688. if ( shaderStage === 'compute' ) {
  56689. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  56690. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  56691. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  56692. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  56693. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  56694. this.enableDirective( 'subgroups', shaderStage );
  56695. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  56696. }
  56697. }
  56698. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  56699. const builtins = this.getBuiltins( 'attribute' );
  56700. if ( builtins ) snippets.push( builtins );
  56701. const attributes = this.getAttributesArray();
  56702. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  56703. const attribute = attributes[ index ];
  56704. const name = attribute.name;
  56705. const type = this.getType( attribute.type );
  56706. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  56707. }
  56708. }
  56709. return snippets.join( ',\n\t' );
  56710. }
  56711. /**
  56712. * Returns the members of the given struct type node as a WGSL string.
  56713. *
  56714. * @param {StructTypeNode} struct - The struct type node.
  56715. * @return {string} The WGSL snippet that defines the struct members.
  56716. */
  56717. getStructMembers( struct ) {
  56718. const snippets = [];
  56719. for ( const member of struct.members ) {
  56720. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  56721. let type = this.getType( member.type );
  56722. if ( member.atomic ) {
  56723. type = 'atomic< ' + type + ' >';
  56724. }
  56725. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  56726. }
  56727. if ( struct.output ) {
  56728. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  56729. }
  56730. return snippets.join( ',\n' );
  56731. }
  56732. /**
  56733. * Returns the structs of the given shader stage as a WGSL string.
  56734. *
  56735. * @param {string} shaderStage - The shader stage.
  56736. * @return {string} The WGSL snippet that defines the structs.
  56737. */
  56738. getStructs( shaderStage ) {
  56739. let result = '';
  56740. const structs = this.structs[ shaderStage ];
  56741. if ( structs.length > 0 ) {
  56742. const snippets = [];
  56743. for ( const struct of structs ) {
  56744. let snippet = `struct ${ struct.name } {\n`;
  56745. snippet += this.getStructMembers( struct );
  56746. snippet += '\n};';
  56747. snippets.push( snippet );
  56748. }
  56749. result = '\n' + snippets.join( '\n\n' ) + '\n';
  56750. }
  56751. return result;
  56752. }
  56753. /**
  56754. * Returns a WGSL string representing a variable.
  56755. *
  56756. * @param {string} type - The variable's type.
  56757. * @param {string} name - The variable's name.
  56758. * @param {?number} [count=null] - The array length.
  56759. * @param {string} [qualifier=''] - The variable's qualifier.
  56760. * @return {string} The WGSL snippet that defines a variable.
  56761. */
  56762. getVar( type, name, count = null, qualifier = '' ) {
  56763. let snippet = `var${ qualifier } ${ name } : `;
  56764. if ( count !== null ) {
  56765. snippet += this.generateArrayDeclaration( type, count );
  56766. } else {
  56767. snippet += this.getType( type );
  56768. }
  56769. return snippet;
  56770. }
  56771. /**
  56772. * Returns the variables of the given shader stage as a WGSL string.
  56773. *
  56774. * @param {string} shaderStage - The shader stage.
  56775. * @return {string} The WGSL snippet that defines the variables.
  56776. */
  56777. getVars( shaderStage, global = false ) {
  56778. let qualifier = '';
  56779. if ( global ) {
  56780. qualifier = '<private>';
  56781. }
  56782. const snippets = [];
  56783. const vars = this.vars[ shaderStage ];
  56784. if ( vars !== undefined ) {
  56785. for ( const variable of vars ) {
  56786. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count, qualifier ) };` );
  56787. }
  56788. }
  56789. return global ? snippets.join( '\n' ) : `\n\t${ snippets.join( '\n\t' ) }\n`;
  56790. }
  56791. /**
  56792. * Returns the varyings of the given shader stage as a WGSL string.
  56793. *
  56794. * @param {string} shaderStage - The shader stage.
  56795. * @return {string} The WGSL snippet that defines the varyings.
  56796. */
  56797. getVaryings( shaderStage ) {
  56798. const snippets = [];
  56799. if ( shaderStage === 'vertex' ) {
  56800. this.getBuiltin( 'position', 'builtinClipSpace', 'vec4<f32>', 'vertex' );
  56801. }
  56802. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  56803. const varyings = this.varyings;
  56804. const vars = this.vars[ shaderStage ];
  56805. let varyingIndex = 0;
  56806. for ( let index = 0; index < varyings.length; index ++ ) {
  56807. const varying = varyings[ index ];
  56808. if ( varying.needsInterpolation ) {
  56809. let attributesSnippet = `@location( ${ varyingIndex ++ } )`;
  56810. if ( varying.interpolationType ) {
  56811. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  56812. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  56813. // Otherwise, optimize interpolation when sensible
  56814. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  56815. attributesSnippet += ' @interpolate(flat, either)';
  56816. }
  56817. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  56818. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  56819. vars.push( varying );
  56820. }
  56821. }
  56822. }
  56823. const builtins = this.getBuiltins( shaderStage );
  56824. if ( builtins ) snippets.push( builtins );
  56825. const code = snippets.join( ',\n\t' );
  56826. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  56827. }
  56828. isCustomStruct( nodeUniform ) {
  56829. const attribute = nodeUniform.value;
  56830. const bufferNode = nodeUniform.node;
  56831. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  56832. const isStructArray =
  56833. ( bufferNode.value && bufferNode.value.array ) &&
  56834. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  56835. return isAttributeStructType && ! isStructArray;
  56836. }
  56837. /**
  56838. * Returns the uniforms of the given shader stage as a WGSL string.
  56839. *
  56840. * @param {string} shaderStage - The shader stage.
  56841. * @return {string} The WGSL snippet that defines the uniforms.
  56842. */
  56843. getUniforms( shaderStage ) {
  56844. const backend = this.renderer.backend;
  56845. const uniforms = this.uniforms[ shaderStage ];
  56846. const bindingSnippets = [];
  56847. const bufferSnippets = [];
  56848. const structSnippets = [];
  56849. const uniformGroups = {};
  56850. for ( const uniform of uniforms ) {
  56851. const groupName = uniform.groupNode.name;
  56852. const uniformIndexes = this.bindingsIndexes[ groupName ];
  56853. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'cubeDepthTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  56854. const textureNode = uniform.node;
  56855. const texture = textureNode.value;
  56856. // Cube textures always need samplers (they use textureSampleLevel, not textureLoad)
  56857. // Also textureGather always need sampler.
  56858. const needsSampler = texture.isCubeTexture === true || ( this.isUnfilterable( texture ) === false && textureNode.isStorageTextureNode !== true ) || textureNode.gatherNode !== null;
  56859. if ( needsSampler ) {
  56860. if ( this.isSampleCompare( texture ) && textureNode.compareNode !== null ) {
  56861. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  56862. } else {
  56863. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  56864. }
  56865. }
  56866. let textureType;
  56867. let multisampled = '';
  56868. const { primarySamples } = backend.utils.getTextureSampleData( texture );
  56869. if ( primarySamples > 1 ) {
  56870. multisampled = '_multisampled';
  56871. }
  56872. if ( texture.isCubeTexture === true && texture.isDepthTexture === true ) {
  56873. textureType = 'texture_depth_cube';
  56874. } else if ( texture.isCubeTexture === true ) {
  56875. textureType = 'texture_cube<f32>';
  56876. } else if ( texture.isDepthTexture === true ) {
  56877. if ( backend.compatibilityMode && texture.compareFunction === null ) {
  56878. textureType = `texture${ multisampled }_2d<f32>`;
  56879. } else {
  56880. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  56881. }
  56882. } else if ( uniform.node.isStorageTextureNode === true ) {
  56883. const format = getFormat( texture, backend.device );
  56884. const access = this.getStorageAccess( uniform.node, shaderStage );
  56885. const is3D = uniform.node.value.is3DTexture;
  56886. const isArrayTexture = uniform.node.value.isArrayTexture;
  56887. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  56888. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  56889. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  56890. textureType = 'texture_2d_array<f32>';
  56891. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  56892. textureType = 'texture_3d<f32>';
  56893. } else {
  56894. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  56895. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  56896. }
  56897. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  56898. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  56899. const bufferNode = uniform.node;
  56900. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  56901. const bufferCount = bufferNode.bufferCount;
  56902. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  56903. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  56904. if ( this.isCustomStruct( uniform ) ) {
  56905. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  56906. } else {
  56907. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  56908. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  56909. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  56910. }
  56911. } else {
  56912. const groupName = uniform.groupNode.name;
  56913. // Check if this group has already been processed in this shader stage
  56914. if ( uniformGroups[ groupName ] === undefined ) {
  56915. // Get the shared uniform group that contains uniforms from all stages
  56916. const sharedUniformGroup = this.uniformGroups[ groupName ];
  56917. if ( sharedUniformGroup !== undefined ) {
  56918. // Generate snippets for ALL uniforms in this shared group
  56919. const snippets = [];
  56920. for ( const sharedUniform of sharedUniformGroup.uniforms ) {
  56921. const type = sharedUniform.getType();
  56922. const vectorType = this.getType( this.getVectorType( type ) );
  56923. snippets.push( `\t${ sharedUniform.name } : ${ vectorType }` );
  56924. }
  56925. // Check if this group already has an assigned binding index (from another shader stage)
  56926. let groupBinding = this.uniformGroupsBindings[ groupName ];
  56927. if ( groupBinding === undefined ) {
  56928. // First time processing this group - assign a new binding index
  56929. groupBinding = {
  56930. index: uniformIndexes.binding ++,
  56931. id: uniformIndexes.group
  56932. };
  56933. this.uniformGroupsBindings[ groupName ] = groupBinding;
  56934. }
  56935. uniformGroups[ groupName ] = {
  56936. index: groupBinding.index,
  56937. id: groupBinding.id,
  56938. snippets: snippets
  56939. };
  56940. }
  56941. }
  56942. }
  56943. }
  56944. for ( const name in uniformGroups ) {
  56945. const group = uniformGroups[ name ];
  56946. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  56947. }
  56948. const code = [ ...bindingSnippets, ...bufferSnippets, ...structSnippets ].join( '\n' );
  56949. return code;
  56950. }
  56951. /**
  56952. * Controls the code build of the shader stages.
  56953. */
  56954. buildCode() {
  56955. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  56956. this.sortBindingGroups();
  56957. for ( const shaderStage in shadersData ) {
  56958. this.shaderStage = shaderStage;
  56959. const allowGlobal = this.allowGlobalVariables;
  56960. const stageData = shadersData[ shaderStage ];
  56961. stageData.uniforms = this.getUniforms( shaderStage );
  56962. stageData.attributes = this.getAttributes( shaderStage );
  56963. stageData.varyings = this.getVaryings( shaderStage );
  56964. stageData.structs = this.getStructs( shaderStage );
  56965. stageData.vars = this.getVars( shaderStage, allowGlobal );
  56966. stageData.codes = this.getCodes( shaderStage );
  56967. stageData.directives = this.getDirectives( shaderStage );
  56968. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  56969. //
  56970. let flow = '// code\n\n';
  56971. flow += this.flowCode[ shaderStage ];
  56972. const flowNodes = this.flowNodes[ shaderStage ];
  56973. const mainNode = flowNodes[ flowNodes.length - 1 ];
  56974. const outputNode = mainNode.outputNode;
  56975. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  56976. for ( const node of flowNodes ) {
  56977. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  56978. const slotName = node.name;
  56979. if ( slotName ) {
  56980. if ( flow.length > 0 ) flow += '\n';
  56981. flow += `\t// flow -> ${ slotName }\n`;
  56982. }
  56983. flow += `${ flowSlotData.code }\n\t`;
  56984. if ( node === mainNode && shaderStage !== 'compute' ) {
  56985. flow += '// result\n\n\t';
  56986. if ( shaderStage === 'vertex' ) {
  56987. flow += `varyings.builtinClipSpace = ${ flowSlotData.result };`;
  56988. } else if ( shaderStage === 'fragment' ) {
  56989. if ( isOutputStruct ) {
  56990. stageData.returnType = outputNode.getNodeType( this );
  56991. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  56992. flow += `return ${ flowSlotData.result };`;
  56993. } else {
  56994. let structSnippet = `\t@location( 0 ) color: ${ this.getType( this.getOutputType() ) }`;
  56995. const builtins = this.getBuiltins( 'output' );
  56996. if ( builtins ) structSnippet += ',\n\t' + builtins;
  56997. stageData.returnType = 'OutputStruct';
  56998. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  56999. stageData.structs += '\nvar<private> output : OutputStruct;';
  57000. flow += `output.color = ${ this.format( flowSlotData.result, mainNode.getNodeType( this ), this.getOutputType() ) };\n\n\treturn output;`;
  57001. }
  57002. }
  57003. }
  57004. }
  57005. stageData.flow = flow;
  57006. }
  57007. this.shaderStage = null;
  57008. if ( this.material !== null ) {
  57009. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  57010. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  57011. } else {
  57012. // Early strictly validated in computeNode
  57013. const workgroupSize = this.object.workgroupSize;
  57014. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  57015. }
  57016. }
  57017. /**
  57018. * Returns the native shader method name for a given generic name.
  57019. *
  57020. * @param {string} method - The method name to resolve.
  57021. * @param {?string} [output=null] - An optional output.
  57022. * @return {string} The resolved WGSL method name.
  57023. */
  57024. getMethod( method, output = null ) {
  57025. let wgslMethod;
  57026. if ( output !== null ) {
  57027. wgslMethod = this._getWGSLMethod( method + '_' + output );
  57028. }
  57029. if ( wgslMethod === undefined ) {
  57030. wgslMethod = this._getWGSLMethod( method );
  57031. }
  57032. return wgslMethod || method;
  57033. }
  57034. /**
  57035. * Returns the bitcast method name for a given input and outputType.
  57036. *
  57037. * @param {string} type - The output type to bitcast to.
  57038. * @return {string} The resolved WGSL bitcast invocation.
  57039. */
  57040. getBitcastMethod( type ) {
  57041. const dataType = this.getType( type );
  57042. return `bitcast<${ dataType }>`;
  57043. }
  57044. /**
  57045. * Returns the float packing method name for a given numeric encoding.
  57046. *
  57047. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  57048. * @returns {string} The resolve WGSL float packing method name.
  57049. */
  57050. getFloatPackingMethod( encoding ) {
  57051. return this.getMethod( `floatpack_${ encoding }_2x16` );
  57052. }
  57053. /**
  57054. * Returns the float unpacking method name for a given numeric encoding.
  57055. *
  57056. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  57057. * @returns {string} The resolve WGSL float unpacking method name.
  57058. */
  57059. getFloatUnpackingMethod( encoding ) {
  57060. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  57061. }
  57062. /**
  57063. * Returns the native snippet for a ternary operation.
  57064. *
  57065. * @param {string} condSnippet - The condition determining which expression gets resolved.
  57066. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  57067. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  57068. * @return {string} The resolved method name.
  57069. */
  57070. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  57071. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  57072. }
  57073. /**
  57074. * Returns the WGSL type of the given node data type.
  57075. *
  57076. * @param {string} type - The node data type.
  57077. * @return {string} The WGSL type.
  57078. */
  57079. getType( type ) {
  57080. return wgslTypeLib[ type ] || type;
  57081. }
  57082. /**
  57083. * Whether the requested feature is available or not.
  57084. *
  57085. * @param {string} name - The requested feature.
  57086. * @return {boolean} Whether the requested feature is supported or not.
  57087. */
  57088. isAvailable( name ) {
  57089. let result = supports[ name ];
  57090. if ( result === undefined ) {
  57091. if ( name === 'float32Filterable' ) {
  57092. result = this.renderer.hasFeature( 'float32-filterable' );
  57093. } else if ( name === 'clipDistance' ) {
  57094. result = this.renderer.hasFeature( 'clip-distances' );
  57095. }
  57096. supports[ name ] = result;
  57097. }
  57098. return result;
  57099. }
  57100. /**
  57101. * Returns the native shader method name for a given generic name.
  57102. *
  57103. * @private
  57104. * @param {string} method - The method name to resolve.
  57105. * @return {string} The resolved WGSL method name.
  57106. */
  57107. _getWGSLMethod( method ) {
  57108. if ( wgslPolyfill[ method ] !== undefined ) {
  57109. this._include( method );
  57110. }
  57111. return wgslMethods[ method ];
  57112. }
  57113. /**
  57114. * Includes the given method name into the current
  57115. * function node.
  57116. *
  57117. * @private
  57118. * @param {string} name - The method name to include.
  57119. * @return {CodeNode} The respective code node.
  57120. */
  57121. _include( name ) {
  57122. const codeNode = wgslPolyfill[ name ];
  57123. codeNode.build( this );
  57124. this.addInclude( codeNode );
  57125. return codeNode;
  57126. }
  57127. /**
  57128. * Returns a WGSL vertex shader based on the given shader data.
  57129. *
  57130. * @private
  57131. * @param {Object} shaderData - The shader data.
  57132. * @return {string} The vertex shader.
  57133. */
  57134. _getWGSLVertexCode( shaderData ) {
  57135. return `${ this.getSignature() }
  57136. // directives
  57137. ${shaderData.directives}
  57138. // structs
  57139. ${shaderData.structs}
  57140. // uniforms
  57141. ${shaderData.uniforms}
  57142. // varyings
  57143. ${shaderData.varyings}
  57144. var<private> varyings : VaryingsStruct;
  57145. // vars
  57146. ${shaderData.vars}
  57147. // codes
  57148. ${shaderData.codes}
  57149. @vertex
  57150. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  57151. // flow
  57152. ${shaderData.flow}
  57153. return varyings;
  57154. }
  57155. `;
  57156. }
  57157. /**
  57158. * Returns a WGSL fragment shader based on the given shader data.
  57159. *
  57160. * @private
  57161. * @param {Object} shaderData - The shader data.
  57162. * @return {string} The vertex shader.
  57163. */
  57164. _getWGSLFragmentCode( shaderData ) {
  57165. return `${ this.getSignature() }
  57166. // global
  57167. ${ diagnostics }
  57168. // structs
  57169. ${shaderData.structs}
  57170. // uniforms
  57171. ${shaderData.uniforms}
  57172. // vars
  57173. ${shaderData.vars}
  57174. // codes
  57175. ${shaderData.codes}
  57176. @fragment
  57177. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  57178. // flow
  57179. ${shaderData.flow}
  57180. }
  57181. `;
  57182. }
  57183. /**
  57184. * Returns a WGSL compute shader based on the given shader data.
  57185. *
  57186. * @private
  57187. * @param {Object} shaderData - The shader data.
  57188. * @param {string} workgroupSize - The workgroup size.
  57189. * @return {string} The vertex shader.
  57190. */
  57191. _getWGSLComputeCode( shaderData, workgroupSize ) {
  57192. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  57193. return `${ this.getSignature() }
  57194. // directives
  57195. ${ shaderData.directives }
  57196. // system
  57197. var<private> instanceIndex : u32;
  57198. // locals
  57199. ${ shaderData.scopedArrays }
  57200. // structs
  57201. ${ shaderData.structs }
  57202. // uniforms
  57203. ${ shaderData.uniforms }
  57204. // vars
  57205. ${ this.allowGlobalVariables ? shaderData.vars : '' }
  57206. // codes
  57207. ${ shaderData.codes }
  57208. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  57209. fn main( ${ shaderData.attributes } ) {
  57210. // local vars
  57211. ${ this.allowGlobalVariables ? '' : shaderData.vars }
  57212. // system
  57213. instanceIndex = globalId.x
  57214. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  57215. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  57216. // flow
  57217. ${ shaderData.flow }
  57218. }
  57219. `;
  57220. }
  57221. /**
  57222. * Returns a WGSL struct based on the given name and variables.
  57223. *
  57224. * @private
  57225. * @param {string} name - The struct name.
  57226. * @param {string} vars - The struct variables.
  57227. * @return {string} The WGSL snippet representing a struct.
  57228. */
  57229. _getWGSLStruct( name, vars ) {
  57230. return `
  57231. struct ${name} {
  57232. ${vars}
  57233. };`;
  57234. }
  57235. /**
  57236. * Returns a WGSL struct binding.
  57237. *
  57238. * @private
  57239. * @param {string} name - The struct name.
  57240. * @param {string} vars - The struct variables.
  57241. * @param {string} access - The access.
  57242. * @param {number} [binding=0] - The binding index.
  57243. * @param {number} [group=0] - The group index.
  57244. * @return {string} The WGSL snippet representing a struct binding.
  57245. */
  57246. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  57247. const structName = name + 'Struct';
  57248. const structSnippet = this._getWGSLStruct( structName, vars );
  57249. return `${structSnippet}
  57250. @binding( ${ binding } ) @group( ${ group } )
  57251. var<${access}> ${ name } : ${ structName };`;
  57252. }
  57253. }
  57254. const _bufferDescriptor$3 = new GPUBufferDescriptor();
  57255. const _commandEncoderDescriptor$2 = new GPUCommandEncoderDescriptor();
  57256. const typedArraysToVertexFormatPrefix = new Map( [
  57257. [ Int8Array, [ 'sint8', 'snorm8' ]],
  57258. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  57259. [ Int16Array, [ 'sint16', 'snorm16' ]],
  57260. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  57261. [ Int32Array, [ 'sint32', 'snorm32' ]],
  57262. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  57263. [ Float32Array, [ 'float32', ]],
  57264. ] );
  57265. if ( typeof Float16Array !== 'undefined' ) {
  57266. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  57267. }
  57268. const typedAttributeToVertexFormatPrefix = new Map( [
  57269. [ Float16BufferAttribute, [ 'float16', ]],
  57270. ] );
  57271. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  57272. [ Int32Array, 'sint32' ],
  57273. [ Int16Array, 'sint32' ], // patch for INT16
  57274. [ Uint32Array, 'uint32' ],
  57275. [ Uint16Array, 'uint32' ], // patch for UINT16
  57276. [ Float32Array, 'float32' ]
  57277. ] );
  57278. /**
  57279. * A WebGPU backend utility module for managing shader attributes.
  57280. *
  57281. * @private
  57282. */
  57283. class WebGPUAttributeUtils {
  57284. /**
  57285. * Constructs a new utility object.
  57286. *
  57287. * @param {WebGPUBackend} backend - The WebGPU backend.
  57288. */
  57289. constructor( backend ) {
  57290. /**
  57291. * A reference to the WebGPU backend.
  57292. *
  57293. * @type {WebGPUBackend}
  57294. */
  57295. this.backend = backend;
  57296. }
  57297. /**
  57298. * Creates the GPU buffer for the given buffer attribute.
  57299. *
  57300. * @param {BufferAttribute} attribute - The buffer attribute.
  57301. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  57302. */
  57303. createAttribute( attribute, usage ) {
  57304. const bufferAttribute = this._getBufferAttribute( attribute );
  57305. const backend = this.backend;
  57306. const bufferData = backend.get( bufferAttribute );
  57307. let buffer = bufferData.buffer;
  57308. if ( buffer === undefined ) {
  57309. const device = backend.device;
  57310. let array = bufferAttribute.array;
  57311. // patch for INT16 and UINT16
  57312. if ( attribute.normalized === false ) {
  57313. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  57314. array = new Int32Array( array );
  57315. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  57316. array = new Uint32Array( array );
  57317. if ( usage & GPUBufferUsage.INDEX ) {
  57318. for ( let i = 0; i < array.length; i ++ ) {
  57319. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  57320. }
  57321. }
  57322. }
  57323. }
  57324. bufferAttribute.array = array;
  57325. let paddedItemSize;
  57326. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  57327. // WGSL does not support packed vec3 data in storage buffers, pad to vec4
  57328. paddedItemSize = 4;
  57329. } else if ( bufferAttribute.itemSize > 1 && ( bufferAttribute.itemSize * array.BYTES_PER_ELEMENT ) % 4 !== 0 ) {
  57330. // arrayStride must be a multiple of 4
  57331. const byteStride = bufferAttribute.itemSize * array.BYTES_PER_ELEMENT;
  57332. paddedItemSize = ( Math.floor( ( byteStride + 3 ) / 4 ) * 4 ) / array.BYTES_PER_ELEMENT;
  57333. }
  57334. if ( paddedItemSize !== undefined ) {
  57335. const itemSize = bufferAttribute.itemSize;
  57336. const paddedArray = new array.constructor( bufferAttribute.count * paddedItemSize );
  57337. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  57338. paddedArray.set( array.subarray( i * itemSize, i * itemSize + itemSize ), i * paddedItemSize );
  57339. }
  57340. if ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) {
  57341. // update the storage attribute so storage bindings access the padded layout
  57342. bufferAttribute.itemSize = paddedItemSize;
  57343. bufferAttribute.array = paddedArray;
  57344. }
  57345. array = paddedArray;
  57346. // save the original and padded item size so buffer updates can apply the same padding
  57347. bufferData._itemSize = itemSize;
  57348. bufferData._paddedItemSize = paddedItemSize;
  57349. }
  57350. // total buffer size must be a multiple of 4
  57351. const byteLength = array.byteLength;
  57352. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  57353. _bufferDescriptor$3.label = bufferAttribute.name;
  57354. _bufferDescriptor$3.size = size;
  57355. _bufferDescriptor$3.usage = usage;
  57356. _bufferDescriptor$3.mappedAtCreation = true;
  57357. buffer = device.createBuffer( _bufferDescriptor$3 );
  57358. _bufferDescriptor$3.reset();
  57359. new array.constructor( buffer.getMappedRange() ).set( array );
  57360. buffer.unmap();
  57361. bufferData.buffer = buffer;
  57362. }
  57363. }
  57364. /**
  57365. * Updates the GPU buffer of the given buffer attribute.
  57366. *
  57367. * @param {BufferAttribute} attribute - The buffer attribute.
  57368. */
  57369. updateAttribute( attribute ) {
  57370. const bufferAttribute = this._getBufferAttribute( attribute );
  57371. const backend = this.backend;
  57372. const device = backend.device;
  57373. const bufferData = backend.get( bufferAttribute );
  57374. const buffer = backend.get( bufferAttribute ).buffer;
  57375. let array = bufferAttribute.array;
  57376. const itemSize = bufferData._itemSize;
  57377. const paddedItemSize = bufferData._paddedItemSize;
  57378. if ( paddedItemSize !== undefined ) {
  57379. // if the attribute data were padded on upload, apply the same padding on updates.
  57380. array = new array.constructor( bufferAttribute.count * paddedItemSize );
  57381. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  57382. array.set( bufferAttribute.array.subarray( i * itemSize, i * itemSize + itemSize ), i * paddedItemSize );
  57383. }
  57384. if ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) {
  57385. // keep the storage attribute in sync with the padded layout
  57386. bufferAttribute.array = array;
  57387. }
  57388. }
  57389. const updateRanges = bufferAttribute.updateRanges;
  57390. if ( updateRanges.length === 0 ) {
  57391. // Not using update ranges
  57392. device.queue.writeBuffer(
  57393. buffer,
  57394. 0,
  57395. array,
  57396. 0
  57397. );
  57398. } else {
  57399. const isTyped = isTypedArray( array );
  57400. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  57401. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  57402. const range = updateRanges[ i ];
  57403. let dataOffset, size;
  57404. if ( paddedItemSize !== undefined ) {
  57405. const vertexStart = Math.floor( range.start / itemSize );
  57406. const vertexCount = Math.ceil( ( range.start + range.count ) / itemSize ) - vertexStart;
  57407. dataOffset = vertexStart * paddedItemSize * byteOffsetFactor;
  57408. size = vertexCount * paddedItemSize * byteOffsetFactor;
  57409. } else {
  57410. dataOffset = range.start * byteOffsetFactor;
  57411. size = range.count * byteOffsetFactor;
  57412. }
  57413. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  57414. device.queue.writeBuffer(
  57415. buffer,
  57416. bufferOffset,
  57417. array,
  57418. dataOffset,
  57419. size
  57420. );
  57421. }
  57422. bufferAttribute.clearUpdateRanges();
  57423. }
  57424. }
  57425. /**
  57426. * This method creates the vertex buffer layout data which are
  57427. * require when creating a render pipeline for the given render object.
  57428. *
  57429. * @param {RenderObject} renderObject - The render object.
  57430. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  57431. */
  57432. createShaderVertexBuffers( renderObject ) {
  57433. const attributes = renderObject.getAttributes();
  57434. const vertexBuffers = new Map();
  57435. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  57436. const geometryAttribute = attributes[ slot ];
  57437. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  57438. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  57439. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  57440. if ( vertexBufferLayout === undefined ) {
  57441. let arrayStride, stepMode;
  57442. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  57443. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  57444. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  57445. } else {
  57446. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  57447. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  57448. if ( geometryAttribute.itemSize > 1 && arrayStride % 4 !== 0 ) {
  57449. // packed attribute data are padded per vertex on upload
  57450. arrayStride = Math.floor( ( arrayStride + 3 ) / 4 ) * 4;
  57451. }
  57452. }
  57453. // patch for INT16 and UINT16
  57454. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  57455. arrayStride = 4;
  57456. }
  57457. vertexBufferLayout = {
  57458. arrayStride,
  57459. attributes: [],
  57460. stepMode
  57461. };
  57462. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  57463. }
  57464. const format = this._getVertexFormat( geometryAttribute );
  57465. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  57466. vertexBufferLayout.attributes.push( {
  57467. shaderLocation: slot,
  57468. offset,
  57469. format
  57470. } );
  57471. }
  57472. return Array.from( vertexBuffers.values() );
  57473. }
  57474. /**
  57475. * Destroys the GPU buffer of the given buffer attribute.
  57476. *
  57477. * @param {BufferAttribute} attribute - The buffer attribute.
  57478. */
  57479. destroyAttribute( attribute ) {
  57480. const backend = this.backend;
  57481. const data = backend.get( this._getBufferAttribute( attribute ) );
  57482. data.buffer.destroy();
  57483. backend.delete( attribute );
  57484. }
  57485. /**
  57486. * This method performs a readback operation by moving buffer data from
  57487. * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can
  57488. * be used to retain and reuse handles to the intermediate buffers and prevent
  57489. * new allocation.
  57490. *
  57491. * @async
  57492. * @param {BufferAttribute} attribute - The storage buffer attribute to read frm.
  57493. * @param {number} count - The offset from which to start reading the
  57494. * @param {number} offset - The storage buffer attribute.
  57495. * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute.
  57496. * @return {Promise<ArrayBuffer|ReadbackBuffer>} A promise that resolves with the buffer data when the data are ready.
  57497. */
  57498. async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) {
  57499. const backend = this.backend;
  57500. const device = backend.device;
  57501. const data = backend.get( this._getBufferAttribute( attribute ) );
  57502. const bufferGPU = data.buffer;
  57503. const byteLength = count === -1 ? bufferGPU.size - offset : count;
  57504. let readBufferGPU;
  57505. if ( target !== null && target.isReadbackBuffer ) {
  57506. const readbackInfo = backend.get( target );
  57507. if ( target._mapped === true ) {
  57508. throw new Error( 'THREE.WebGPUAttributeUtils: ReadbackBuffer must be released before being used again.' );
  57509. }
  57510. target._mapped = true;
  57511. // initialize the GPU-side read copy buffer if it is not present
  57512. if ( readbackInfo.readBufferGPU === undefined ) {
  57513. _bufferDescriptor$3.label = `${ target.name }_readback`;
  57514. _bufferDescriptor$3.size = target.maxByteLength;
  57515. _bufferDescriptor$3.usage = GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ;
  57516. readBufferGPU = device.createBuffer( _bufferDescriptor$3 );
  57517. _bufferDescriptor$3.reset();
  57518. // release / dispose
  57519. const releaseCallback = () => {
  57520. target.buffer = null;
  57521. target._mapped = false;
  57522. readBufferGPU.unmap();
  57523. };
  57524. const disposeCallback = () => {
  57525. target.buffer = null;
  57526. target._mapped = false;
  57527. readBufferGPU.destroy();
  57528. backend.delete( target );
  57529. target.removeEventListener( 'release', releaseCallback );
  57530. target.removeEventListener( 'dispose', disposeCallback );
  57531. };
  57532. target.addEventListener( 'release', releaseCallback );
  57533. target.addEventListener( 'dispose', disposeCallback );
  57534. // register
  57535. readbackInfo.readBufferGPU = readBufferGPU;
  57536. } else {
  57537. readBufferGPU = readbackInfo.readBufferGPU;
  57538. }
  57539. } else {
  57540. // create a new temp buffer for array buffers otherwise
  57541. _bufferDescriptor$3.label = `${ attribute.name }_readback`;
  57542. _bufferDescriptor$3.size = byteLength;
  57543. _bufferDescriptor$3.usage = GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ;
  57544. readBufferGPU = device.createBuffer( _bufferDescriptor$3 );
  57545. _bufferDescriptor$3.reset();
  57546. }
  57547. // copy the data
  57548. _commandEncoderDescriptor$2.label = `readback_encoder_${ attribute.name }`;
  57549. const cmdEncoder = device.createCommandEncoder( _commandEncoderDescriptor$2 );
  57550. _commandEncoderDescriptor$2.reset();
  57551. cmdEncoder.copyBufferToBuffer(
  57552. bufferGPU,
  57553. offset,
  57554. readBufferGPU,
  57555. 0,
  57556. byteLength,
  57557. );
  57558. const gpuCommands = cmdEncoder.finish();
  57559. submit( device, gpuCommands );
  57560. // map the data to the CPU
  57561. await readBufferGPU.mapAsync( GPUMapMode.READ, 0, byteLength );
  57562. if ( target === null ) {
  57563. // return a new array buffer and clean up the gpu handles
  57564. const arrayBuffer = readBufferGPU.getMappedRange( 0, byteLength );
  57565. const result = arrayBuffer.slice();
  57566. readBufferGPU.destroy();
  57567. return result;
  57568. } else if ( target.isReadbackBuffer ) {
  57569. // assign the data to the read back handle
  57570. target.buffer = readBufferGPU.getMappedRange( 0, byteLength );
  57571. return target;
  57572. } else {
  57573. // copy the data into the target array buffer
  57574. const arrayBuffer = readBufferGPU.getMappedRange( 0, byteLength );
  57575. new Uint8Array( target ).set( new Uint8Array( arrayBuffer ) );
  57576. readBufferGPU.destroy();
  57577. return target;
  57578. }
  57579. }
  57580. /**
  57581. * Returns the vertex format of the given buffer attribute.
  57582. *
  57583. * @private
  57584. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  57585. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  57586. */
  57587. _getVertexFormat( geometryAttribute ) {
  57588. const { itemSize, normalized } = geometryAttribute;
  57589. const ArrayType = geometryAttribute.array.constructor;
  57590. const AttributeType = geometryAttribute.constructor;
  57591. let format;
  57592. if ( itemSize === 1 ) {
  57593. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  57594. } else {
  57595. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  57596. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  57597. if ( prefix ) {
  57598. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  57599. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  57600. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  57601. if ( paddedItemSize % 1 ) {
  57602. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  57603. }
  57604. format = `${prefix}x${paddedItemSize}`;
  57605. }
  57606. }
  57607. if ( ! format ) {
  57608. error( 'WebGPUAttributeUtils: Vertex format not supported yet.' );
  57609. }
  57610. return format;
  57611. }
  57612. /**
  57613. * Utility method for handling interleaved buffer attributes correctly.
  57614. * To process them, their `InterleavedBuffer` is returned.
  57615. *
  57616. * @private
  57617. * @param {BufferAttribute} attribute - The attribute.
  57618. * @return {BufferAttribute|InterleavedBuffer}
  57619. */
  57620. _getBufferAttribute( attribute ) {
  57621. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  57622. return attribute;
  57623. }
  57624. }
  57625. const _bindGroupDescriptor = new GPUBindGroupDescriptor();
  57626. const _bufferDescriptor$2 = new GPUBufferDescriptor();
  57627. const _viewDescriptor$1 = new GPUTextureViewDescriptor();
  57628. /**
  57629. * Class representing a WebGPU bind group layout.
  57630. *
  57631. * @private
  57632. */
  57633. class BindGroupLayout {
  57634. /**
  57635. * Constructs a new layout.
  57636. *
  57637. * @param {GPUBindGroupLayout} layoutGPU - A GPU Bind Group Layout.
  57638. */
  57639. constructor( layoutGPU ) {
  57640. /**
  57641. * The current GPUBindGroupLayout.
  57642. *
  57643. * @type {GPUBindGroupLayout}
  57644. */
  57645. this.layoutGPU = layoutGPU;
  57646. /**
  57647. * The number of bind groups that use this layout.
  57648. *
  57649. * @type {number}
  57650. */
  57651. this.usedTimes = 0;
  57652. }
  57653. }
  57654. /**
  57655. * A WebGPU backend utility module for managing bindings.
  57656. *
  57657. * When reading the documentation it's helpful to keep in mind that
  57658. * all class definitions starting with 'GPU*' are modules from the
  57659. * WebGPU API. So for example `BindGroup` is a class from the engine
  57660. * whereas `GPUBindGroup` is a class from WebGPU.
  57661. *
  57662. * @private
  57663. */
  57664. class WebGPUBindingUtils {
  57665. /**
  57666. * Constructs a new utility object.
  57667. *
  57668. * @param {WebGPUBackend} backend - The WebGPU backend.
  57669. */
  57670. constructor( backend ) {
  57671. /**
  57672. * A reference to the WebGPU backend.
  57673. *
  57674. * @type {WebGPUBackend}
  57675. */
  57676. this.backend = backend;
  57677. /**
  57678. * A cache that maps combinations of layout entries to existing bind group layouts.
  57679. *
  57680. * @private
  57681. * @type {Map<string, BindGroupLayout>}
  57682. */
  57683. this._bindGroupLayoutCache = new Map();
  57684. }
  57685. /**
  57686. * Creates a GPU bind group layout for the given bind group.
  57687. *
  57688. * @param {BindGroup} bindGroup - The bind group.
  57689. * @return {GPUBindGroupLayout} The GPU bind group layout.
  57690. */
  57691. createBindingsLayout( bindGroup ) {
  57692. const backend = this.backend;
  57693. const device = backend.device;
  57694. const bindingsData = backend.get( bindGroup );
  57695. // check if the the bind group already has a layout
  57696. if ( bindingsData.layout ) {
  57697. return bindingsData.layout.layoutGPU;
  57698. }
  57699. // if not, assing one
  57700. const entries = this._createLayoutEntries( bindGroup );
  57701. const bindGroupLayoutKey = hashString( JSON.stringify( entries ) );
  57702. // try to find an existing layout in the cache
  57703. let bindGroupLayout = this._bindGroupLayoutCache.get( bindGroupLayoutKey );
  57704. // if not create a new one
  57705. if ( bindGroupLayout === undefined ) {
  57706. bindGroupLayout = new BindGroupLayout( device.createBindGroupLayout( { entries } ) );
  57707. this._bindGroupLayoutCache.set( bindGroupLayoutKey, bindGroupLayout );
  57708. }
  57709. bindGroupLayout.usedTimes ++;
  57710. bindingsData.layout = bindGroupLayout;
  57711. bindingsData.layoutKey = bindGroupLayoutKey;
  57712. return bindGroupLayout.layoutGPU;
  57713. }
  57714. /**
  57715. * Creates bindings from the given bind group definition.
  57716. *
  57717. * @param {BindGroup} bindGroup - The bind group.
  57718. * @param {Array<BindGroup>} bindings - Array of bind groups.
  57719. * @param {number} cacheIndex - The cache index.
  57720. * @param {number} version - The version.
  57721. */
  57722. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  57723. const { backend } = this;
  57724. const bindingsData = backend.get( bindGroup );
  57725. // setup (static) binding layout and (dynamic) binding group
  57726. const bindLayoutGPU = this.createBindingsLayout( bindGroup );
  57727. let bindGroupGPU;
  57728. if ( cacheIndex > 0 ) {
  57729. if ( bindingsData.groups === undefined ) {
  57730. bindingsData.groups = [];
  57731. bindingsData.versions = [];
  57732. }
  57733. if ( bindingsData.versions[ cacheIndex ] === version ) {
  57734. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  57735. }
  57736. }
  57737. if ( bindGroupGPU === undefined ) {
  57738. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  57739. if ( cacheIndex > 0 ) {
  57740. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  57741. bindingsData.versions[ cacheIndex ] = version;
  57742. }
  57743. }
  57744. bindingsData.group = bindGroupGPU;
  57745. }
  57746. /**
  57747. * Updates a buffer binding.
  57748. *
  57749. * @param {Buffer} binding - The buffer binding to update.
  57750. */
  57751. updateBinding( binding ) {
  57752. const backend = this.backend;
  57753. const device = backend.device;
  57754. const array = binding.buffer; // cpu
  57755. const buffer = backend.get( binding ).buffer; // gpu
  57756. const updateRanges = binding.updateRanges;
  57757. if ( updateRanges.length === 0 ) {
  57758. device.queue.writeBuffer(
  57759. buffer,
  57760. 0,
  57761. array,
  57762. 0
  57763. );
  57764. } else {
  57765. const isTyped = isTypedArray( array );
  57766. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  57767. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  57768. const range = updateRanges[ i ];
  57769. const dataOffset = range.start * byteOffsetFactor;
  57770. const size = range.count * byteOffsetFactor;
  57771. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  57772. device.queue.writeBuffer(
  57773. buffer,
  57774. bufferOffset,
  57775. array,
  57776. dataOffset,
  57777. size
  57778. );
  57779. }
  57780. }
  57781. }
  57782. /**
  57783. * Creates a GPU bind group for the camera index.
  57784. *
  57785. * @param {Uint32Array} data - The index data.
  57786. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  57787. * @return {GPUBindGroup} The GPU bind group.
  57788. */
  57789. createBindGroupIndex( data, layoutGPU ) {
  57790. const backend = this.backend;
  57791. const device = backend.device;
  57792. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  57793. const index = data[ 0 ];
  57794. _bufferDescriptor$2.label = 'bindingCameraIndex_' + index;
  57795. _bufferDescriptor$2.size = 16; // uint(4) * 4
  57796. _bufferDescriptor$2.usage = usage;
  57797. const buffer = device.createBuffer( _bufferDescriptor$2 );
  57798. _bufferDescriptor$2.reset();
  57799. device.queue.writeBuffer( buffer, 0, data, 0 );
  57800. _bindGroupDescriptor.label = 'bindGroupCameraIndex_' + index;
  57801. _bindGroupDescriptor.layout = layoutGPU;
  57802. _bindGroupDescriptor.entries.push( { binding: 0, resource: { buffer } } );
  57803. const bindGroup = device.createBindGroup( _bindGroupDescriptor );
  57804. _bindGroupDescriptor.reset();
  57805. return bindGroup;
  57806. }
  57807. /**
  57808. * Creates a GPU bind group for the given bind group and GPU layout.
  57809. *
  57810. * @param {BindGroup} bindGroup - The bind group.
  57811. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  57812. * @return {GPUBindGroup} The GPU bind group.
  57813. */
  57814. createBindGroup( bindGroup, layoutGPU ) {
  57815. const backend = this.backend;
  57816. const device = backend.device;
  57817. let bindingPoint = 0;
  57818. _bindGroupDescriptor.label = 'bindGroup_' + bindGroup.name;
  57819. _bindGroupDescriptor.layout = layoutGPU;
  57820. for ( const binding of bindGroup.bindings ) {
  57821. if ( binding.isUniformBuffer ) {
  57822. const bindingData = backend.get( binding );
  57823. _bindGroupDescriptor.entries.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  57824. } else if ( binding.isStorageBuffer ) {
  57825. const buffer = backend.get( binding.attribute ).buffer;
  57826. _bindGroupDescriptor.entries.push( { binding: bindingPoint, resource: { buffer: buffer } } );
  57827. } else if ( binding.isSampledTexture ) {
  57828. const textureData = backend.get( binding.texture );
  57829. let resourceGPU;
  57830. if ( textureData.externalTexture !== undefined ) {
  57831. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  57832. } else {
  57833. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  57834. const baseMipLevel = binding.store ? binding.mipLevel : 0;
  57835. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  57836. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  57837. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  57838. }
  57839. propertyName += `-${ mipLevelCount }-${ baseMipLevel }`;
  57840. resourceGPU = textureData[ propertyName ];
  57841. if ( resourceGPU === undefined ) {
  57842. const aspectGPU = GPUTextureAspect.All;
  57843. let dimensionViewGPU;
  57844. if ( binding.isSampledCubeTexture ) {
  57845. dimensionViewGPU = GPUTextureViewDimension.Cube;
  57846. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  57847. // Prefer the texture's actual array flag over the cached 3D binding type.
  57848. // Layered render targets can become array textures after shader compilation.
  57849. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  57850. } else if ( binding.isSampledTexture3D ) {
  57851. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  57852. } else {
  57853. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  57854. }
  57855. _viewDescriptor$1.aspect = aspectGPU;
  57856. _viewDescriptor$1.dimension = dimensionViewGPU;
  57857. _viewDescriptor$1.mipLevelCount = mipLevelCount;
  57858. _viewDescriptor$1.baseMipLevel = baseMipLevel;
  57859. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( _viewDescriptor$1 );
  57860. _viewDescriptor$1.reset();
  57861. }
  57862. }
  57863. _bindGroupDescriptor.entries.push( { binding: bindingPoint, resource: resourceGPU } );
  57864. } else if ( binding.isSampler ) {
  57865. const textureGPU = backend.get( binding.texture );
  57866. _bindGroupDescriptor.entries.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  57867. }
  57868. bindingPoint ++;
  57869. }
  57870. const bindGroupGPU = device.createBindGroup( _bindGroupDescriptor );
  57871. _bindGroupDescriptor.reset();
  57872. return bindGroupGPU;
  57873. }
  57874. /**
  57875. * Creates a GPU bind group layout entries for the given bind group.
  57876. *
  57877. * @private
  57878. * @param {BindGroup} bindGroup - The bind group.
  57879. * @return {Array<GPUBindGroupLayoutEntry>} The GPU bind group layout entries.
  57880. */
  57881. _createLayoutEntries( bindGroup ) {
  57882. const entries = [];
  57883. let index = 0;
  57884. for ( const binding of bindGroup.bindings ) {
  57885. const backend = this.backend;
  57886. const bindingGPU = {
  57887. binding: index,
  57888. visibility: binding.visibility
  57889. };
  57890. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  57891. const buffer = {}; // GPUBufferBindingLayout
  57892. if ( binding.isStorageBuffer ) {
  57893. if ( binding.visibility & GPUShaderStage.COMPUTE ) {
  57894. // compute
  57895. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  57896. buffer.type = GPUBufferBindingType.Storage;
  57897. } else {
  57898. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  57899. }
  57900. } else {
  57901. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  57902. }
  57903. }
  57904. bindingGPU.buffer = buffer;
  57905. } else if ( binding.isSampledTexture && binding.store ) {
  57906. const storageTexture = {}; // GPUStorageTextureBindingLayout
  57907. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  57908. const access = binding.access;
  57909. if ( access === NodeAccess.READ_WRITE ) {
  57910. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  57911. } else if ( access === NodeAccess.WRITE_ONLY ) {
  57912. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  57913. } else {
  57914. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  57915. }
  57916. if ( binding.texture.isArrayTexture ) {
  57917. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  57918. } else if ( binding.texture.is3DTexture ) {
  57919. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  57920. }
  57921. bindingGPU.storageTexture = storageTexture;
  57922. } else if ( binding.isSampledTexture ) {
  57923. const texture = {}; // GPUTextureBindingLayout
  57924. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  57925. if ( primarySamples > 1 ) {
  57926. texture.multisampled = true;
  57927. if ( ! binding.texture.isDepthTexture ) {
  57928. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  57929. }
  57930. }
  57931. if ( binding.texture.isDepthTexture ) {
  57932. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  57933. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  57934. } else {
  57935. texture.sampleType = GPUTextureSampleType.Depth;
  57936. }
  57937. } else {
  57938. const type = binding.texture.type;
  57939. if ( type === IntType ) {
  57940. texture.sampleType = GPUTextureSampleType.SInt;
  57941. } else if ( type === UnsignedIntType ) {
  57942. texture.sampleType = GPUTextureSampleType.UInt;
  57943. } else if ( type === FloatType ) {
  57944. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  57945. texture.sampleType = GPUTextureSampleType.Float;
  57946. } else {
  57947. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  57948. }
  57949. }
  57950. }
  57951. if ( binding.isSampledCubeTexture ) {
  57952. texture.viewDimension = GPUTextureViewDimension.Cube;
  57953. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  57954. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  57955. } else if ( binding.isSampledTexture3D ) {
  57956. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  57957. }
  57958. bindingGPU.texture = texture;
  57959. } else if ( binding.isSampler ) {
  57960. const sampler = {}; // GPUSamplerBindingLayout
  57961. if ( binding.texture.isDepthTexture ) {
  57962. if ( binding.texture.compareFunction !== null && binding.textureNode.compareNode !== null && backend.hasCompatibility( Compatibility.TEXTURE_COMPARE ) ) {
  57963. sampler.type = GPUSamplerBindingType.Comparison;
  57964. } else {
  57965. // Depth textures without compare must use non-filtering sampler
  57966. sampler.type = GPUSamplerBindingType.NonFiltering;
  57967. }
  57968. }
  57969. bindingGPU.sampler = sampler;
  57970. } else {
  57971. error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  57972. }
  57973. entries.push( bindingGPU );
  57974. index ++;
  57975. }
  57976. return entries;
  57977. }
  57978. /**
  57979. * Delete the data associated with a bind group.
  57980. *
  57981. * @param {BindGroup} bindGroup - The bind group.
  57982. */
  57983. deleteBindGroupData( bindGroup ) {
  57984. const { backend } = this;
  57985. const bindingsData = backend.get( bindGroup );
  57986. if ( bindingsData.layout ) {
  57987. bindingsData.layout.usedTimes --;
  57988. if ( bindingsData.layout.usedTimes === 0 ) {
  57989. this._bindGroupLayoutCache.delete( bindingsData.layoutKey );
  57990. }
  57991. bindingsData.layout = undefined;
  57992. bindingsData.layoutKey = undefined;
  57993. }
  57994. }
  57995. /**
  57996. * Frees internal resources.
  57997. */
  57998. dispose() {
  57999. this._bindGroupLayoutCache.clear();
  58000. }
  58001. }
  58002. /**
  58003. * A WebGPU backend utility module for managing the device's capabilities.
  58004. *
  58005. * @private
  58006. */
  58007. class WebGPUCapabilities {
  58008. /**
  58009. * Constructs a new utility object.
  58010. *
  58011. * @param {WebGPUBackend} backend - The WebGPU backend.
  58012. */
  58013. constructor( backend ) {
  58014. /**
  58015. * A reference to the WebGPU backend.
  58016. *
  58017. * @type {WebGPUBackend}
  58018. */
  58019. this.backend = backend;
  58020. }
  58021. /**
  58022. * Returns the maximum anisotropy texture filtering value.
  58023. *
  58024. * @return {number} The maximum anisotropy texture filtering value.
  58025. */
  58026. getMaxAnisotropy() {
  58027. return 16;
  58028. }
  58029. /**
  58030. * Returns the maximum number of bytes available for uniform buffers.
  58031. *
  58032. * @return {number} The maximum number of bytes available for uniform buffers.
  58033. */
  58034. getUniformBufferLimit() {
  58035. return this.backend.device.limits.maxUniformBufferBindingSize;
  58036. }
  58037. }
  58038. /**
  58039. * Reusable descriptor for `GPUDevice.createComputePipeline()`.
  58040. *
  58041. * @private
  58042. */
  58043. class GPUComputePipelineDescriptor {
  58044. constructor() {
  58045. /**
  58046. * The label of the compute pipeline.
  58047. *
  58048. * @type {string}
  58049. */
  58050. this.label = '';
  58051. /**
  58052. * The pipeline layout the pipeline conforms to, or `'auto'`.
  58053. *
  58054. * @type {?GPUPipelineLayout|string}
  58055. * @default null
  58056. */
  58057. this.layout = null;
  58058. /**
  58059. * The programmable compute stage.
  58060. *
  58061. * @type {?Object}
  58062. * @default null
  58063. */
  58064. this.compute = null;
  58065. }
  58066. /**
  58067. * Resets the descriptor to its default state.
  58068. */
  58069. reset() {
  58070. this.label = '';
  58071. this.layout = null;
  58072. this.compute = null;
  58073. }
  58074. }
  58075. /**
  58076. * Reusable descriptor for `GPUDevice.createPipelineLayout()`.
  58077. *
  58078. * @private
  58079. */
  58080. class GPUPipelineLayoutDescriptor {
  58081. constructor() {
  58082. /**
  58083. * The label of the pipeline layout.
  58084. *
  58085. * @type {string}
  58086. */
  58087. this.label = '';
  58088. /**
  58089. * The set of bind group layouts the pipeline layout describes.
  58090. *
  58091. * @type {?Array<?GPUBindGroupLayout>}
  58092. * @default null
  58093. */
  58094. this.bindGroupLayouts = null;
  58095. }
  58096. /**
  58097. * Resets the descriptor to its default state.
  58098. */
  58099. reset() {
  58100. this.label = '';
  58101. this.bindGroupLayouts = null;
  58102. }
  58103. }
  58104. const _computePipelineDescriptor = new GPUComputePipelineDescriptor();
  58105. const _pipelineLayoutDescriptor = new GPUPipelineLayoutDescriptor();
  58106. const _renderBundleEncoderDescriptor = new GPURenderBundleEncoderDescriptor();
  58107. const _renderPipelineDescriptor = new GPURenderPipelineDescriptor();
  58108. /**
  58109. * A WebGPU backend utility module for managing pipelines.
  58110. *
  58111. * @private
  58112. */
  58113. class WebGPUPipelineUtils {
  58114. /**
  58115. * Constructs a new utility object.
  58116. *
  58117. * @param {WebGPUBackend} backend - The WebGPU backend.
  58118. */
  58119. constructor( backend ) {
  58120. /**
  58121. * A reference to the WebGPU backend.
  58122. *
  58123. * @type {WebGPUBackend}
  58124. */
  58125. this.backend = backend;
  58126. }
  58127. /**
  58128. * Returns the sample count derived from the given render context.
  58129. *
  58130. * @private
  58131. * @param {RenderContext} renderContext - The render context.
  58132. * @return {number} The sample count.
  58133. */
  58134. _getSampleCount( renderContext ) {
  58135. return this.backend.utils.getSampleCountRenderContext( renderContext );
  58136. }
  58137. /**
  58138. * Creates a render pipeline for the given render object.
  58139. *
  58140. * @param {RenderObject} renderObject - The render object.
  58141. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  58142. */
  58143. createRenderPipeline( renderObject, promises ) {
  58144. const { object, material, geometry, pipeline } = renderObject;
  58145. const { vertexProgram, fragmentProgram } = pipeline;
  58146. const backend = this.backend;
  58147. const device = backend.device;
  58148. const utils = backend.utils;
  58149. const pipelineData = backend.get( pipeline );
  58150. // bind group layouts
  58151. const bindGroupLayouts = [];
  58152. for ( const bindGroup of renderObject.getBindings() ) {
  58153. const bindingsData = backend.get( bindGroup );
  58154. const { layoutGPU } = bindingsData.layout;
  58155. bindGroupLayouts.push( layoutGPU );
  58156. }
  58157. // vertex buffers
  58158. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  58159. // material blending
  58160. let materialBlending;
  58161. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  58162. materialBlending = this._getBlending( material );
  58163. }
  58164. // stencil
  58165. let stencilFront = {};
  58166. if ( material.stencilWrite === true ) {
  58167. stencilFront = {
  58168. compare: this._getStencilCompare( material ),
  58169. failOp: this._getStencilOperation( material.stencilFail ),
  58170. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  58171. passOp: this._getStencilOperation( material.stencilZPass )
  58172. };
  58173. }
  58174. const colorWriteMask = this._getColorWriteMask( material );
  58175. const targets = [];
  58176. if ( renderObject.context.textures !== null ) {
  58177. const textures = renderObject.context.textures;
  58178. const mrt = renderObject.context.mrt;
  58179. for ( let i = 0; i < textures.length; i ++ ) {
  58180. const texture = textures[ i ];
  58181. const colorFormat = utils.getTextureFormatGPU( texture );
  58182. // mrt blending
  58183. let blending;
  58184. if ( mrt !== null ) {
  58185. if ( this.backend.compatibilityMode !== true ) {
  58186. const blendMode = mrt.getBlendMode( texture.name );
  58187. if ( blendMode.blending === MaterialBlending ) {
  58188. blending = materialBlending;
  58189. } else if ( blendMode.blending !== NoBlending ) {
  58190. blending = this._getBlending( blendMode );
  58191. }
  58192. } else {
  58193. 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.' );
  58194. blending = materialBlending;
  58195. }
  58196. } else {
  58197. blending = materialBlending;
  58198. }
  58199. targets.push( {
  58200. format: colorFormat,
  58201. blend: blending,
  58202. writeMask: colorWriteMask
  58203. } );
  58204. }
  58205. } else {
  58206. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  58207. targets.push( {
  58208. format: colorFormat,
  58209. blend: materialBlending,
  58210. writeMask: colorWriteMask
  58211. } );
  58212. }
  58213. const vertexModule = backend.get( vertexProgram ).module;
  58214. const fragmentModule = backend.get( fragmentProgram ).module;
  58215. const primitiveState = this._getPrimitiveState( object, geometry, material );
  58216. const depthCompare = this._getDepthCompare( material );
  58217. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  58218. const sampleCount = this._getSampleCount( renderObject.context );
  58219. _pipelineLayoutDescriptor.bindGroupLayouts = bindGroupLayouts;
  58220. const pipelineLayout = device.createPipelineLayout( _pipelineLayoutDescriptor );
  58221. _pipelineLayoutDescriptor.reset();
  58222. _renderPipelineDescriptor.label = `renderPipeline_${ material.name || material.type }_${ material.id }`;
  58223. _renderPipelineDescriptor.vertex = Object.assign( {}, vertexModule, { buffers: vertexBuffers } );
  58224. _renderPipelineDescriptor.fragment = Object.assign( {}, fragmentModule, { targets } );
  58225. _renderPipelineDescriptor.primitive = primitiveState;
  58226. _renderPipelineDescriptor.multisample.count = sampleCount;
  58227. _renderPipelineDescriptor.multisample.alphaToCoverageEnabled = material.alphaToCoverage && sampleCount > 1;
  58228. _renderPipelineDescriptor.layout = pipelineLayout;
  58229. const depthStencil = {};
  58230. const renderDepth = renderObject.context.depth;
  58231. const renderStencil = renderObject.context.stencil;
  58232. if ( renderDepth === true || renderStencil === true ) {
  58233. if ( renderDepth === true ) {
  58234. depthStencil.format = depthStencilFormat;
  58235. depthStencil.depthWriteEnabled = material.depthWrite;
  58236. depthStencil.depthCompare = depthCompare;
  58237. }
  58238. if ( renderStencil === true ) {
  58239. depthStencil.stencilFront = stencilFront;
  58240. depthStencil.stencilBack = stencilFront; // apply the same stencil ops to both faces, matching gl.stencilOp() which is not face-separated
  58241. depthStencil.stencilReadMask = material.stencilFuncMask;
  58242. depthStencil.stencilWriteMask = material.stencilWriteMask;
  58243. }
  58244. if ( material.polygonOffset === true && ( primitiveState.topology === GPUPrimitiveTopology.TriangleList ) ) {
  58245. depthStencil.depthBias = material.polygonOffsetUnits;
  58246. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  58247. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  58248. }
  58249. _renderPipelineDescriptor.depthStencil = depthStencil;
  58250. }
  58251. // create pipeline
  58252. device.pushErrorScope( 'validation' );
  58253. const stages = [
  58254. { program: vertexProgram, module: vertexModule.module },
  58255. { program: fragmentProgram, module: fragmentModule.module }
  58256. ];
  58257. const pipelineLabel = _renderPipelineDescriptor.label;
  58258. if ( promises === null ) {
  58259. pipelineData.pipeline = device.createRenderPipeline( _renderPipelineDescriptor );
  58260. _renderPipelineDescriptor.reset();
  58261. device.popErrorScope().then( ( err ) => {
  58262. if ( err !== null ) {
  58263. pipelineData.error = true;
  58264. error( `WebGPURenderer: Render pipeline creation failed (${ pipelineLabel }): ${ err.message }` );
  58265. this._reportShaderDiagnostics( stages, pipelineLabel );
  58266. }
  58267. } );
  58268. } else {
  58269. const p = new Promise( async ( resolve /*, reject*/ ) => {
  58270. try {
  58271. let asyncError = null;
  58272. let pipelinePromise = null;
  58273. try {
  58274. pipelinePromise = device.createRenderPipelineAsync( _renderPipelineDescriptor );
  58275. } catch ( err ) {
  58276. asyncError = err;
  58277. }
  58278. _renderPipelineDescriptor.reset();
  58279. if ( pipelinePromise !== null ) {
  58280. try {
  58281. pipelineData.pipeline = await pipelinePromise;
  58282. } catch ( err ) {
  58283. asyncError = err;
  58284. }
  58285. }
  58286. const errorScope = await device.popErrorScope();
  58287. if ( errorScope !== null || asyncError !== null ) {
  58288. pipelineData.error = true;
  58289. const reason = ( errorScope && errorScope.message ) || ( asyncError && asyncError.message ) || 'unknown';
  58290. error( `WebGPURenderer: Async render pipeline creation failed (${ pipelineLabel }): ${ reason }` );
  58291. await this._reportShaderDiagnostics( stages, pipelineLabel );
  58292. }
  58293. } finally {
  58294. // Guarantee resolution so `compileAsync`'s Promise.all cannot hang on an
  58295. // unexpected throw from any await above.
  58296. resolve();
  58297. }
  58298. } );
  58299. promises.push( p );
  58300. }
  58301. }
  58302. /**
  58303. * Creates GPU render bundle encoder for the given render context.
  58304. *
  58305. * @param {RenderContext} renderContext - The render context.
  58306. * @param {?string} [label='renderBundleEncoder'] - The label.
  58307. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  58308. */
  58309. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  58310. const backend = this.backend;
  58311. const { utils, device } = backend;
  58312. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  58313. const colorFormats = utils.getCurrentColorFormats( renderContext );
  58314. const sampleCount = this._getSampleCount( renderContext );
  58315. _renderBundleEncoderDescriptor.label = label;
  58316. _renderBundleEncoderDescriptor.colorFormats = colorFormats;
  58317. _renderBundleEncoderDescriptor.depthStencilFormat = depthStencilFormat;
  58318. _renderBundleEncoderDescriptor.sampleCount = sampleCount;
  58319. const bundleEncoder = device.createRenderBundleEncoder( _renderBundleEncoderDescriptor );
  58320. _renderBundleEncoderDescriptor.reset();
  58321. return bundleEncoder;
  58322. }
  58323. /**
  58324. * Creates a compute pipeline for the given compute node.
  58325. *
  58326. * @param {ComputePipeline} pipeline - The compute pipeline.
  58327. * @param {Array<BindGroup>} bindings - The bindings.
  58328. */
  58329. createComputePipeline( pipeline, bindings ) {
  58330. const backend = this.backend;
  58331. const device = backend.device;
  58332. const computeProgram = backend.get( pipeline.computeProgram ).module;
  58333. const pipelineGPU = backend.get( pipeline );
  58334. // bind group layouts
  58335. const bindGroupLayouts = [];
  58336. for ( const bindingsGroup of bindings ) {
  58337. const bindingsData = backend.get( bindingsGroup );
  58338. const { layoutGPU } = bindingsData.layout;
  58339. bindGroupLayouts.push( layoutGPU );
  58340. }
  58341. const computeStage = pipeline.computeProgram;
  58342. const pipelineLabel = `computePipeline_${ computeStage.stage }${ computeStage.name ? `_${ computeStage.name }` : '' }`;
  58343. device.pushErrorScope( 'validation' );
  58344. _pipelineLayoutDescriptor.bindGroupLayouts = bindGroupLayouts;
  58345. const pipelineLayout = device.createPipelineLayout( _pipelineLayoutDescriptor );
  58346. _pipelineLayoutDescriptor.reset();
  58347. _computePipelineDescriptor.label = pipelineLabel;
  58348. _computePipelineDescriptor.compute = computeProgram;
  58349. _computePipelineDescriptor.layout = pipelineLayout;
  58350. pipelineGPU.pipeline = device.createComputePipeline( _computePipelineDescriptor );
  58351. _computePipelineDescriptor.reset();
  58352. device.popErrorScope().then( ( err ) => {
  58353. if ( err !== null ) {
  58354. pipelineGPU.error = true;
  58355. error( `WebGPURenderer: Compute pipeline creation failed (${ pipelineLabel }): ${ err.message }` );
  58356. this._reportShaderDiagnostics( [ { program: computeStage, module: computeProgram.module } ], pipelineLabel );
  58357. }
  58358. } );
  58359. }
  58360. /**
  58361. * Reads line-accurate diagnostics from shader modules and logs them.
  58362. * Called from pipeline creation error paths to turn opaque validation
  58363. * failures into actionable WGSL feedback.
  58364. *
  58365. * @private
  58366. * @param {Array<{program: ProgrammableStage, module: GPUShaderModule}>} stages - Pairs of program + compiled shader module.
  58367. * @param {string} pipelineLabel - Label of the owning pipeline, used as log prefix.
  58368. * @return {Promise<void>}
  58369. */
  58370. async _reportShaderDiagnostics( stages, pipelineLabel ) {
  58371. for ( const { program, module } of stages ) {
  58372. const info = await module.getCompilationInfo();
  58373. if ( info.messages.length === 0 ) continue;
  58374. const sourceLines = program.code.split( '\n' );
  58375. for ( const msg of info.messages ) {
  58376. const location = msg.lineNum > 0
  58377. ? ` at line ${ msg.lineNum }${ msg.linePos > 0 ? `:${ msg.linePos }` : '' }`
  58378. : '';
  58379. const header = `WebGPURenderer [${ pipelineLabel } / ${ program.stage } ${ msg.type }]${ location }: ${ msg.message }`;
  58380. let excerpt = '';
  58381. if ( msg.lineNum > 0 && msg.lineNum <= sourceLines.length ) {
  58382. excerpt = `\n ${ sourceLines[ msg.lineNum - 1 ] }`;
  58383. if ( msg.linePos > 0 ) excerpt += `\n ${ ' '.repeat( msg.linePos - 1 ) }^`;
  58384. }
  58385. ( msg.type === 'error' ? error : warn )( header + excerpt );
  58386. }
  58387. }
  58388. }
  58389. /**
  58390. * Returns the blending state as a descriptor object required
  58391. * for the pipeline creation.
  58392. *
  58393. * @private
  58394. * @param {Material|BlendMode} object - The object containing blending information.
  58395. * @return {Object} The blending state.
  58396. */
  58397. _getBlending( object ) {
  58398. let color, alpha;
  58399. const blending = object.blending;
  58400. const blendSrc = object.blendSrc;
  58401. const blendDst = object.blendDst;
  58402. const blendEquation = object.blendEquation;
  58403. if ( blending === CustomBlending ) {
  58404. const blendSrcAlpha = object.blendSrcAlpha !== null ? object.blendSrcAlpha : blendSrc;
  58405. const blendDstAlpha = object.blendDstAlpha !== null ? object.blendDstAlpha : blendDst;
  58406. const blendEquationAlpha = object.blendEquationAlpha !== null ? object.blendEquationAlpha : blendEquation;
  58407. color = {
  58408. srcFactor: this._getBlendFactor( blendSrc ),
  58409. dstFactor: this._getBlendFactor( blendDst ),
  58410. operation: this._getBlendOperation( blendEquation )
  58411. };
  58412. alpha = {
  58413. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  58414. dstFactor: this._getBlendFactor( blendDstAlpha ),
  58415. operation: this._getBlendOperation( blendEquationAlpha )
  58416. };
  58417. } else {
  58418. const premultipliedAlpha = object.premultipliedAlpha;
  58419. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  58420. color = {
  58421. srcFactor: srcRGB,
  58422. dstFactor: dstRGB,
  58423. operation: GPUBlendOperation.Add
  58424. };
  58425. alpha = {
  58426. srcFactor: srcAlpha,
  58427. dstFactor: dstAlpha,
  58428. operation: GPUBlendOperation.Add
  58429. };
  58430. };
  58431. if ( premultipliedAlpha ) {
  58432. switch ( blending ) {
  58433. case NormalBlending:
  58434. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  58435. break;
  58436. case AdditiveBlending:
  58437. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  58438. break;
  58439. case SubtractiveBlending:
  58440. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  58441. break;
  58442. case MultiplyBlending:
  58443. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  58444. break;
  58445. }
  58446. } else {
  58447. switch ( blending ) {
  58448. case NormalBlending:
  58449. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  58450. break;
  58451. case AdditiveBlending:
  58452. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  58453. break;
  58454. case SubtractiveBlending:
  58455. error( `WebGPURenderer: "SubtractiveBlending" requires "${ object.isMaterial ? 'material' : 'blendMode' }.premultipliedAlpha = true".` );
  58456. break;
  58457. case MultiplyBlending:
  58458. error( `WebGPURenderer: "MultiplyBlending" requires "${ object.isMaterial ? 'material' : 'blendMode' }.premultipliedAlpha = true".` );
  58459. break;
  58460. }
  58461. }
  58462. }
  58463. if ( color !== undefined && alpha !== undefined ) {
  58464. return { color, alpha };
  58465. } else {
  58466. error( 'WebGPURenderer: Invalid blending: ', blending );
  58467. }
  58468. }
  58469. /**
  58470. * Returns the GPU blend factor which is required for the pipeline creation.
  58471. *
  58472. * @private
  58473. * @param {number} blend - The blend factor as a three.js constant.
  58474. * @return {string} The GPU blend factor.
  58475. */
  58476. _getBlendFactor( blend ) {
  58477. let blendFactor;
  58478. switch ( blend ) {
  58479. case ZeroFactor:
  58480. blendFactor = GPUBlendFactor.Zero;
  58481. break;
  58482. case OneFactor:
  58483. blendFactor = GPUBlendFactor.One;
  58484. break;
  58485. case SrcColorFactor:
  58486. blendFactor = GPUBlendFactor.Src;
  58487. break;
  58488. case OneMinusSrcColorFactor:
  58489. blendFactor = GPUBlendFactor.OneMinusSrc;
  58490. break;
  58491. case SrcAlphaFactor:
  58492. blendFactor = GPUBlendFactor.SrcAlpha;
  58493. break;
  58494. case OneMinusSrcAlphaFactor:
  58495. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  58496. break;
  58497. case DstColorFactor:
  58498. blendFactor = GPUBlendFactor.Dst;
  58499. break;
  58500. case OneMinusDstColorFactor:
  58501. blendFactor = GPUBlendFactor.OneMinusDst;
  58502. break;
  58503. case DstAlphaFactor:
  58504. blendFactor = GPUBlendFactor.DstAlpha;
  58505. break;
  58506. case OneMinusDstAlphaFactor:
  58507. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  58508. break;
  58509. case SrcAlphaSaturateFactor:
  58510. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  58511. break;
  58512. case BlendColorFactor:
  58513. blendFactor = GPUBlendFactor.Constant;
  58514. break;
  58515. case OneMinusBlendColorFactor:
  58516. blendFactor = GPUBlendFactor.OneMinusConstant;
  58517. break;
  58518. default:
  58519. error( 'WebGPURenderer: Blend factor not supported.', blend );
  58520. }
  58521. return blendFactor;
  58522. }
  58523. /**
  58524. * Returns the GPU stencil compare function which is required for the pipeline creation.
  58525. *
  58526. * @private
  58527. * @param {Material} material - The material.
  58528. * @return {string} The GPU stencil compare function.
  58529. */
  58530. _getStencilCompare( material ) {
  58531. let stencilCompare;
  58532. const stencilFunc = material.stencilFunc;
  58533. switch ( stencilFunc ) {
  58534. case NeverStencilFunc:
  58535. stencilCompare = GPUCompareFunction.Never;
  58536. break;
  58537. case AlwaysStencilFunc:
  58538. stencilCompare = GPUCompareFunction.Always;
  58539. break;
  58540. case LessStencilFunc:
  58541. stencilCompare = GPUCompareFunction.Less;
  58542. break;
  58543. case LessEqualStencilFunc:
  58544. stencilCompare = GPUCompareFunction.LessEqual;
  58545. break;
  58546. case EqualStencilFunc:
  58547. stencilCompare = GPUCompareFunction.Equal;
  58548. break;
  58549. case GreaterEqualStencilFunc:
  58550. stencilCompare = GPUCompareFunction.GreaterEqual;
  58551. break;
  58552. case GreaterStencilFunc:
  58553. stencilCompare = GPUCompareFunction.Greater;
  58554. break;
  58555. case NotEqualStencilFunc:
  58556. stencilCompare = GPUCompareFunction.NotEqual;
  58557. break;
  58558. default:
  58559. error( 'WebGPURenderer: Invalid stencil function.', stencilFunc );
  58560. }
  58561. return stencilCompare;
  58562. }
  58563. /**
  58564. * Returns the GPU stencil operation which is required for the pipeline creation.
  58565. *
  58566. * @private
  58567. * @param {number} op - A three.js constant defining the stencil operation.
  58568. * @return {string} The GPU stencil operation.
  58569. */
  58570. _getStencilOperation( op ) {
  58571. let stencilOperation;
  58572. switch ( op ) {
  58573. case KeepStencilOp:
  58574. stencilOperation = GPUStencilOperation.Keep;
  58575. break;
  58576. case ZeroStencilOp:
  58577. stencilOperation = GPUStencilOperation.Zero;
  58578. break;
  58579. case ReplaceStencilOp:
  58580. stencilOperation = GPUStencilOperation.Replace;
  58581. break;
  58582. case InvertStencilOp:
  58583. stencilOperation = GPUStencilOperation.Invert;
  58584. break;
  58585. case IncrementStencilOp:
  58586. stencilOperation = GPUStencilOperation.IncrementClamp;
  58587. break;
  58588. case DecrementStencilOp:
  58589. stencilOperation = GPUStencilOperation.DecrementClamp;
  58590. break;
  58591. case IncrementWrapStencilOp:
  58592. stencilOperation = GPUStencilOperation.IncrementWrap;
  58593. break;
  58594. case DecrementWrapStencilOp:
  58595. stencilOperation = GPUStencilOperation.DecrementWrap;
  58596. break;
  58597. default:
  58598. error( 'WebGPURenderer: Invalid stencil operation.', stencilOperation );
  58599. }
  58600. return stencilOperation;
  58601. }
  58602. /**
  58603. * Returns the GPU blend operation which is required for the pipeline creation.
  58604. *
  58605. * @private
  58606. * @param {number} blendEquation - A three.js constant defining the blend equation.
  58607. * @return {string} The GPU blend operation.
  58608. */
  58609. _getBlendOperation( blendEquation ) {
  58610. let blendOperation;
  58611. switch ( blendEquation ) {
  58612. case AddEquation:
  58613. blendOperation = GPUBlendOperation.Add;
  58614. break;
  58615. case SubtractEquation:
  58616. blendOperation = GPUBlendOperation.Subtract;
  58617. break;
  58618. case ReverseSubtractEquation:
  58619. blendOperation = GPUBlendOperation.ReverseSubtract;
  58620. break;
  58621. case MinEquation:
  58622. blendOperation = GPUBlendOperation.Min;
  58623. break;
  58624. case MaxEquation:
  58625. blendOperation = GPUBlendOperation.Max;
  58626. break;
  58627. default:
  58628. error( 'WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  58629. }
  58630. return blendOperation;
  58631. }
  58632. /**
  58633. * Returns the primitive state as a descriptor object required
  58634. * for the pipeline creation.
  58635. *
  58636. * @private
  58637. * @param {Object3D} object - The 3D object.
  58638. * @param {BufferGeometry} geometry - The geometry.
  58639. * @param {Material} material - The material.
  58640. * @return {Object} The primitive state.
  58641. */
  58642. _getPrimitiveState( object, geometry, material ) {
  58643. const descriptor = {};
  58644. const utils = this.backend.utils;
  58645. //
  58646. descriptor.topology = utils.getPrimitiveTopology( object, material );
  58647. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  58648. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  58649. }
  58650. //
  58651. let flipSided = ( material.side === BackSide );
  58652. if ( object.isMesh && object.matrixWorld.determinant() < 0 ) flipSided = ! flipSided;
  58653. descriptor.frontFace = ( flipSided === true ) ? GPUFrontFace.CW : GPUFrontFace.CCW;
  58654. //
  58655. descriptor.cullMode = ( material.side === DoubleSide ) ? GPUCullMode.None : GPUCullMode.Back;
  58656. return descriptor;
  58657. }
  58658. /**
  58659. * Returns the GPU color write mask which is required for the pipeline creation.
  58660. *
  58661. * @private
  58662. * @param {Material} material - The material.
  58663. * @return {number} The GPU color write mask.
  58664. */
  58665. _getColorWriteMask( material ) {
  58666. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  58667. }
  58668. /**
  58669. * Returns the GPU depth compare function which is required for the pipeline creation.
  58670. *
  58671. * @private
  58672. * @param {Material} material - The material.
  58673. * @return {string} The GPU depth compare function.
  58674. */
  58675. _getDepthCompare( material ) {
  58676. let depthCompare;
  58677. if ( material.depthTest === false ) {
  58678. depthCompare = GPUCompareFunction.Always;
  58679. } else {
  58680. const depthFunc = ( this.backend.parameters.reversedDepthBuffer ) ? ReversedDepthFuncs[ material.depthFunc ] : material.depthFunc;
  58681. switch ( depthFunc ) {
  58682. case NeverDepth:
  58683. depthCompare = GPUCompareFunction.Never;
  58684. break;
  58685. case AlwaysDepth:
  58686. depthCompare = GPUCompareFunction.Always;
  58687. break;
  58688. case LessDepth:
  58689. depthCompare = GPUCompareFunction.Less;
  58690. break;
  58691. case LessEqualDepth:
  58692. depthCompare = GPUCompareFunction.LessEqual;
  58693. break;
  58694. case EqualDepth:
  58695. depthCompare = GPUCompareFunction.Equal;
  58696. break;
  58697. case GreaterEqualDepth:
  58698. depthCompare = GPUCompareFunction.GreaterEqual;
  58699. break;
  58700. case GreaterDepth:
  58701. depthCompare = GPUCompareFunction.Greater;
  58702. break;
  58703. case NotEqualDepth:
  58704. depthCompare = GPUCompareFunction.NotEqual;
  58705. break;
  58706. default:
  58707. error( 'WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  58708. }
  58709. }
  58710. return depthCompare;
  58711. }
  58712. }
  58713. /**
  58714. * Reusable descriptor for `GPUDevice.createQuerySet()`.
  58715. *
  58716. * @private
  58717. */
  58718. class GPUQuerySetDescriptor {
  58719. constructor() {
  58720. /**
  58721. * The label of the query set.
  58722. *
  58723. * @type {string}
  58724. */
  58725. this.label = '';
  58726. /**
  58727. * The type of queries managed by the set.
  58728. *
  58729. * @type {string|undefined}
  58730. */
  58731. this.type = undefined;
  58732. /**
  58733. * The number of queries managed by the set.
  58734. *
  58735. * @type {number}
  58736. * @default 0
  58737. */
  58738. this.count = 0;
  58739. }
  58740. /**
  58741. * Resets the descriptor to its default state.
  58742. */
  58743. reset() {
  58744. this.label = '';
  58745. this.type = undefined;
  58746. this.count = 0;
  58747. }
  58748. }
  58749. const _bufferDescriptor$1 = new GPUBufferDescriptor();
  58750. const _commandEncoderDescriptor$1 = new GPUCommandEncoderDescriptor();
  58751. const _querySetDescriptor$1 = new GPUQuerySetDescriptor();
  58752. /**
  58753. * Manages a pool of WebGPU timestamp queries for performance measurement.
  58754. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  58755. *
  58756. * @augments TimestampQueryPool
  58757. */
  58758. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  58759. /**
  58760. * Creates a new WebGPU timestamp query pool.
  58761. *
  58762. * @param {GPUDevice} device - The WebGPU device to create queries on.
  58763. * @param {string} type - The type identifier for this query pool.
  58764. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  58765. */
  58766. constructor( device, type, maxQueries = 2048 ) {
  58767. super( maxQueries );
  58768. this.device = device;
  58769. this.type = type;
  58770. _querySetDescriptor$1.label = `queryset_global_timestamp_${type}`;
  58771. _querySetDescriptor$1.type = 'timestamp';
  58772. _querySetDescriptor$1.count = this.maxQueries;
  58773. this.querySet = this.device.createQuerySet( _querySetDescriptor$1 );
  58774. _querySetDescriptor$1.reset();
  58775. const bufferSize = this.maxQueries * 8;
  58776. _bufferDescriptor$1.label = `buffer_timestamp_resolve_${type}`;
  58777. _bufferDescriptor$1.size = bufferSize;
  58778. _bufferDescriptor$1.usage = GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC;
  58779. this.resolveBuffer = this.device.createBuffer( _bufferDescriptor$1 );
  58780. _bufferDescriptor$1.reset();
  58781. _bufferDescriptor$1.label = `buffer_timestamp_result_${type}`;
  58782. _bufferDescriptor$1.size = bufferSize;
  58783. _bufferDescriptor$1.usage = GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ;
  58784. this.resultBuffer = this.device.createBuffer( _bufferDescriptor$1 );
  58785. _bufferDescriptor$1.reset();
  58786. }
  58787. /**
  58788. * Allocates a pair of queries for a given render context.
  58789. *
  58790. * @param {string} uid - A unique identifier for the render context.
  58791. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  58792. */
  58793. allocateQueriesForContext( uid ) {
  58794. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  58795. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  58796. 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() } ).` );
  58797. return null;
  58798. }
  58799. const baseOffset = this.currentQueryIndex;
  58800. this.currentQueryIndex += 2;
  58801. this.queryOffsets.set( uid, baseOffset );
  58802. return baseOffset;
  58803. }
  58804. /**
  58805. * Asynchronously resolves all pending queries and returns the total duration.
  58806. * If there's already a pending resolve operation, returns that promise instead.
  58807. *
  58808. * @async
  58809. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  58810. */
  58811. async resolveQueriesAsync() {
  58812. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  58813. return this.lastValue;
  58814. }
  58815. if ( this.pendingResolve ) {
  58816. return this.pendingResolve;
  58817. }
  58818. this.pendingResolve = this._resolveQueries();
  58819. try {
  58820. const result = await this.pendingResolve;
  58821. return result;
  58822. } finally {
  58823. this.pendingResolve = null;
  58824. }
  58825. }
  58826. /**
  58827. * Internal method to resolve queries and calculate total duration.
  58828. *
  58829. * @async
  58830. * @private
  58831. * @returns {Promise<number>} The total duration in milliseconds.
  58832. */
  58833. async _resolveQueries() {
  58834. if ( this.isDisposed ) {
  58835. return this.lastValue;
  58836. }
  58837. try {
  58838. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  58839. return this.lastValue;
  58840. }
  58841. const currentOffsets = new Map( this.queryOffsets );
  58842. const queryCount = this.currentQueryIndex;
  58843. const bytesUsed = queryCount * 8;
  58844. // Reset state before GPU work
  58845. this.currentQueryIndex = 0;
  58846. this.queryOffsets.clear();
  58847. const commandEncoder = this.device.createCommandEncoder( _commandEncoderDescriptor$1 );
  58848. commandEncoder.resolveQuerySet(
  58849. this.querySet,
  58850. 0,
  58851. queryCount,
  58852. this.resolveBuffer,
  58853. 0
  58854. );
  58855. commandEncoder.copyBufferToBuffer(
  58856. this.resolveBuffer,
  58857. 0,
  58858. this.resultBuffer,
  58859. 0,
  58860. bytesUsed
  58861. );
  58862. const commandBuffer = commandEncoder.finish();
  58863. submit( this.device, commandBuffer );
  58864. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  58865. return this.lastValue;
  58866. }
  58867. // Create and track the mapping operation
  58868. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  58869. if ( this.isDisposed ) {
  58870. if ( this.resultBuffer.mapState === 'mapped' ) {
  58871. this.resultBuffer.unmap();
  58872. }
  58873. return this.lastValue;
  58874. }
  58875. //
  58876. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  58877. const framesDuration = {};
  58878. const frames = [];
  58879. for ( const [ uid, baseOffset ] of currentOffsets ) {
  58880. const match = uid.match( /^(.*):f(\d+)$/ );
  58881. const frame = parseInt( match[ 2 ] );
  58882. if ( frames.includes( frame ) === false ) {
  58883. frames.push( frame );
  58884. }
  58885. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  58886. const startTime = times[ baseOffset ];
  58887. const endTime = times[ baseOffset + 1 ];
  58888. const duration = Number( endTime - startTime ) / 1e6;
  58889. this.timestamps.set( uid, duration );
  58890. framesDuration[ frame ] += duration;
  58891. }
  58892. // Return the total duration of the last frame
  58893. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  58894. this.resultBuffer.unmap();
  58895. this.lastValue = totalDuration;
  58896. this.frames = frames;
  58897. return totalDuration;
  58898. } catch ( e ) {
  58899. error( 'Error resolving queries:', e );
  58900. if ( this.resultBuffer.mapState === 'mapped' ) {
  58901. this.resultBuffer.unmap();
  58902. }
  58903. return this.lastValue;
  58904. }
  58905. }
  58906. /**
  58907. * Dispose of the query pool.
  58908. *
  58909. * @async
  58910. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  58911. */
  58912. async dispose() {
  58913. if ( this.isDisposed ) {
  58914. return;
  58915. }
  58916. this.isDisposed = true;
  58917. // Wait for pending resolve operation
  58918. if ( this.pendingResolve ) {
  58919. try {
  58920. await this.pendingResolve;
  58921. } catch ( e ) {
  58922. error( 'Error waiting for pending resolve:', e );
  58923. }
  58924. }
  58925. // Ensure buffer is unmapped before destroying
  58926. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  58927. try {
  58928. this.resultBuffer.unmap();
  58929. } catch ( e ) {
  58930. error( 'Error unmapping buffer:', e );
  58931. }
  58932. }
  58933. // Destroy resources
  58934. if ( this.querySet ) {
  58935. this.querySet.destroy();
  58936. this.querySet = null;
  58937. }
  58938. if ( this.resolveBuffer ) {
  58939. this.resolveBuffer.destroy();
  58940. this.resolveBuffer = null;
  58941. }
  58942. if ( this.resultBuffer ) {
  58943. this.resultBuffer.destroy();
  58944. this.resultBuffer = null;
  58945. }
  58946. this.queryOffsets.clear();
  58947. this.pendingResolve = null;
  58948. }
  58949. }
  58950. /**
  58951. * Reusable descriptor for `GPUCommandEncoder.beginComputePass()`.
  58952. *
  58953. * @private
  58954. */
  58955. class GPUComputePassDescriptor {
  58956. constructor() {
  58957. /**
  58958. * The label of the compute pass.
  58959. *
  58960. * @type {string}
  58961. */
  58962. this.label = '';
  58963. /**
  58964. * Defines which timestamp values are written and where.
  58965. *
  58966. * @type {Object|undefined}
  58967. */
  58968. this.timestampWrites = undefined;
  58969. }
  58970. /**
  58971. * Resets the descriptor to its default state.
  58972. */
  58973. reset() {
  58974. this.label = '';
  58975. this.timestampWrites = undefined;
  58976. }
  58977. }
  58978. /**
  58979. * Reusable descriptor for `GPURenderPassDepthStencilAttachment`, the
  58980. * `depthStencilAttachment` field of `GPURenderPassDescriptor`.
  58981. *
  58982. * @private
  58983. */
  58984. class GPURenderPassDepthStencilAttachment {
  58985. constructor() {
  58986. /**
  58987. * The depth/stencil texture view the pass renders into.
  58988. *
  58989. * @type {?GPUTextureView}
  58990. * @default null
  58991. */
  58992. this.view = null;
  58993. /**
  58994. * The load operation applied to the depth aspect at the start of the pass.
  58995. *
  58996. * @type {string|undefined}
  58997. */
  58998. this.depthLoadOp = undefined;
  58999. /**
  59000. * The store operation applied to the depth aspect at the end of the pass.
  59001. *
  59002. * @type {string|undefined}
  59003. */
  59004. this.depthStoreOp = undefined;
  59005. /**
  59006. * The clear value used when `depthLoadOp` is `'clear'`.
  59007. *
  59008. * @type {number|undefined}
  59009. */
  59010. this.depthClearValue = undefined;
  59011. /**
  59012. * Whether the depth aspect is read-only.
  59013. *
  59014. * @type {boolean}
  59015. * @default false
  59016. */
  59017. this.depthReadOnly = false;
  59018. /**
  59019. * The load operation applied to the stencil aspect at the start of the pass.
  59020. *
  59021. * @type {string|undefined}
  59022. */
  59023. this.stencilLoadOp = undefined;
  59024. /**
  59025. * The store operation applied to the stencil aspect at the end of the pass.
  59026. *
  59027. * @type {string|undefined}
  59028. */
  59029. this.stencilStoreOp = undefined;
  59030. /**
  59031. * The clear value used when `stencilLoadOp` is `'clear'`.
  59032. *
  59033. * @type {number}
  59034. * @default 0
  59035. */
  59036. this.stencilClearValue = 0;
  59037. /**
  59038. * Whether the stencil aspect is read-only.
  59039. *
  59040. * @type {boolean}
  59041. * @default false
  59042. */
  59043. this.stencilReadOnly = false;
  59044. }
  59045. /**
  59046. * Resets the descriptor to its default state.
  59047. */
  59048. reset() {
  59049. this.view = null;
  59050. this.depthLoadOp = undefined;
  59051. this.depthStoreOp = undefined;
  59052. this.depthClearValue = undefined;
  59053. this.depthReadOnly = false;
  59054. this.stencilLoadOp = undefined;
  59055. this.stencilStoreOp = undefined;
  59056. this.stencilClearValue = 0;
  59057. this.stencilReadOnly = false;
  59058. }
  59059. }
  59060. /**
  59061. * Reusable descriptor for `GPURenderPassTimestampWrites`, the
  59062. * `timestampWrites` field of `GPURenderPassDescriptor`. The same shape is
  59063. * also accepted as `GPUComputePassTimestampWrites`.
  59064. *
  59065. * @private
  59066. */
  59067. class GPURenderPassTimestampWrites {
  59068. constructor() {
  59069. /**
  59070. * The query set the timestamps are written to.
  59071. *
  59072. * @type {?GPUQuerySet}
  59073. * @default null
  59074. */
  59075. this.querySet = null;
  59076. /**
  59077. * The index in the query set the beginning timestamp is written to.
  59078. *
  59079. * @type {number|undefined}
  59080. */
  59081. this.beginningOfPassWriteIndex = undefined;
  59082. /**
  59083. * The index in the query set the ending timestamp is written to.
  59084. *
  59085. * @type {number|undefined}
  59086. */
  59087. this.endOfPassWriteIndex = undefined;
  59088. }
  59089. /**
  59090. * Resets the descriptor to its default state.
  59091. */
  59092. reset() {
  59093. this.querySet = null;
  59094. this.beginningOfPassWriteIndex = undefined;
  59095. this.endOfPassWriteIndex = undefined;
  59096. }
  59097. }
  59098. // debugger tools
  59099. // import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  59100. const _clearValue = { r: 0, g: 0, b: 0, a: 1 };
  59101. const _bufferDescriptor = new GPUBufferDescriptor();
  59102. const _commandEncoderDescriptor = new GPUCommandEncoderDescriptor();
  59103. const _computePassDescriptor = new GPUComputePassDescriptor();
  59104. const _querySetDescriptor = new GPUQuerySetDescriptor();
  59105. const _shaderModuleDescriptor = new GPUShaderModuleDescriptor();
  59106. const _renderPassTimestampWrites = new GPURenderPassTimestampWrites();
  59107. const _texelCopyTextureInfoSrc = new GPUTexelCopyTextureInfo();
  59108. const _texelCopyTextureInfoDst = new GPUTexelCopyTextureInfo();
  59109. const _viewDescriptor = new GPUTextureViewDescriptor();
  59110. const _extent3D = new GPUExtent3D();
  59111. /**
  59112. * A backend implementation targeting WebGPU.
  59113. *
  59114. * @private
  59115. * @augments Backend
  59116. */
  59117. class WebGPUBackend extends Backend {
  59118. /**
  59119. * WebGPUBackend options.
  59120. *
  59121. * @typedef {Object} WebGPUBackend~Options
  59122. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  59123. * @property {boolean} [reversedDepthBuffer=false] - Whether reversed depth buffer is enabled or not.
  59124. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  59125. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  59126. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  59127. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  59128. * @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.
  59129. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  59130. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  59131. * @property {string} [powerPreference=undefined] - The power preference.
  59132. * @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.
  59133. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  59134. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  59135. */
  59136. /**
  59137. * Constructs a new WebGPU backend.
  59138. *
  59139. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  59140. */
  59141. constructor( parameters = {} ) {
  59142. super( parameters );
  59143. /**
  59144. * This flag can be used for type testing.
  59145. *
  59146. * @type {boolean}
  59147. * @readonly
  59148. * @default true
  59149. */
  59150. this.isWebGPUBackend = true;
  59151. // some parameters require default values other than "undefined"
  59152. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  59153. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  59154. /**
  59155. * Indicates whether the backend is in WebGPU compatibility mode or not.
  59156. * The backend must be initialized before the property can be evaluated.
  59157. *
  59158. * @type {?boolean}
  59159. * @readonly
  59160. * @default null
  59161. */
  59162. this.compatibilityMode = null;
  59163. /**
  59164. * A reference to the device.
  59165. *
  59166. * @type {?GPUDevice}
  59167. * @default null
  59168. */
  59169. this.device = null;
  59170. /**
  59171. * A reference to the default render pass descriptor.
  59172. *
  59173. * @type {?Object}
  59174. * @default null
  59175. */
  59176. this.defaultRenderPassdescriptor = null;
  59177. /**
  59178. * A reference to a backend module holding common utility functions.
  59179. *
  59180. * @type {WebGPUUtils}
  59181. */
  59182. this.utils = new WebGPUUtils( this );
  59183. /**
  59184. * A reference to a backend module holding shader attribute-related
  59185. * utility functions.
  59186. *
  59187. * @type {WebGPUAttributeUtils}
  59188. */
  59189. this.attributeUtils = new WebGPUAttributeUtils( this );
  59190. /**
  59191. * A reference to a backend module holding shader binding-related
  59192. * utility functions.
  59193. *
  59194. * @type {WebGPUBindingUtils}
  59195. */
  59196. this.bindingUtils = new WebGPUBindingUtils( this );
  59197. /**
  59198. * A reference to a backend module holding device capability related
  59199. * utility functions.
  59200. *
  59201. * @type {WebGPUCapabilities}
  59202. */
  59203. this.capabilities = new WebGPUCapabilities( this );
  59204. /**
  59205. * A reference to a backend module holding shader pipeline-related
  59206. * utility functions.
  59207. *
  59208. * @type {WebGPUPipelineUtils}
  59209. */
  59210. this.pipelineUtils = new WebGPUPipelineUtils( this );
  59211. /**
  59212. * A reference to a backend module holding shader texture-related
  59213. * utility functions.
  59214. *
  59215. * @type {WebGPUTextureUtils}
  59216. */
  59217. this.textureUtils = new WebGPUTextureUtils( this );
  59218. /**
  59219. * A map that manages the resolve buffers for occlusion queries.
  59220. *
  59221. * @type {Map<number,GPUBuffer>}
  59222. */
  59223. this.occludedResolveCache = new Map();
  59224. // compatibility checks
  59225. const compatibilityTextureCompare = typeof navigator === 'undefined' ? true : /Android/.test( navigator.userAgent ) === false;
  59226. /**
  59227. * A map of compatibility checks.
  59228. *
  59229. * @type {Object}
  59230. */
  59231. this._compatibility = {
  59232. [ Compatibility.TEXTURE_COMPARE ]: compatibilityTextureCompare
  59233. };
  59234. }
  59235. /**
  59236. * Initializes the backend so it is ready for usage.
  59237. *
  59238. * @async
  59239. * @param {Renderer} renderer - The renderer.
  59240. * @return {Promise} A Promise that resolves when the backend has been initialized.
  59241. */
  59242. async init( renderer ) {
  59243. await super.init( renderer );
  59244. //
  59245. const parameters = this.parameters;
  59246. // create the device if it is not passed with parameters
  59247. let device;
  59248. if ( parameters.device === undefined ) {
  59249. const adapterOptions = {
  59250. powerPreference: parameters.powerPreference,
  59251. featureLevel: 'compatibility',
  59252. xrCompatible: renderer.xr.enabled
  59253. };
  59254. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  59255. if ( adapter === null ) {
  59256. throw new Error( 'THREE.WebGPUBackend: Unable to create WebGPU adapter.' );
  59257. }
  59258. // feature support
  59259. const features = Object.values( GPUFeatureName );
  59260. const supportedFeatures = [];
  59261. for ( const name of features ) {
  59262. if ( adapter.features.has( name ) ) {
  59263. supportedFeatures.push( name );
  59264. }
  59265. }
  59266. const deviceDescriptor = {
  59267. requiredFeatures: supportedFeatures,
  59268. requiredLimits: parameters.requiredLimits
  59269. };
  59270. device = await adapter.requestDevice( deviceDescriptor );
  59271. } else {
  59272. device = parameters.device;
  59273. }
  59274. this.compatibilityMode = ! device.features.has( 'core-features-and-limits' );
  59275. if ( this.compatibilityMode ) {
  59276. renderer._samples = 0;
  59277. }
  59278. device.lost.then( ( info ) => {
  59279. if ( info.reason === 'destroyed' ) return;
  59280. const deviceLossInfo = {
  59281. api: 'WebGPU',
  59282. message: info.message || 'Unknown reason',
  59283. reason: info.reason || null,
  59284. originalEvent: info
  59285. };
  59286. renderer.onDeviceLost( deviceLossInfo );
  59287. } );
  59288. device.onuncapturederror = ( event ) => {
  59289. const gpuError = event.error;
  59290. const type = gpuError && gpuError.constructor ? gpuError.constructor.name : 'GPUError';
  59291. const message = ( gpuError && gpuError.message ) || 'Unknown uncaptured GPU error';
  59292. renderer.onError( {
  59293. api: 'WebGPU',
  59294. type,
  59295. message,
  59296. originalEvent: event
  59297. } );
  59298. };
  59299. this.device = device;
  59300. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  59301. this.updateSize();
  59302. }
  59303. /**
  59304. * Registers external GPU textures from `XRGPUBinding` for use in rendering.
  59305. *
  59306. * @param {RenderTarget} renderTarget - The render target to register the textures for.
  59307. * @param {GPUTexture} colorTexture - The shared XR color GPUTexture.
  59308. * @param {?Array<Object>} [viewDescriptors=null] - Optional view descriptors, one per XR view.
  59309. */
  59310. setXRRenderTargetTextures( renderTarget, colorTexture, viewDescriptors = null ) {
  59311. this.set( renderTarget.texture, {
  59312. texture: colorTexture,
  59313. format: colorTexture.format,
  59314. externalTexture: true,
  59315. xrViewDescriptors: viewDescriptors,
  59316. initialized: true
  59317. } );
  59318. }
  59319. /**
  59320. * A reference to the context.
  59321. *
  59322. * @type {?GPUCanvasContext}
  59323. * @default null
  59324. */
  59325. get context() {
  59326. const canvasTarget = this.renderer.getCanvasTarget();
  59327. const canvasData = this.get( canvasTarget );
  59328. let context = canvasData.context;
  59329. if ( context === undefined ) {
  59330. const parameters = this.parameters;
  59331. if ( canvasTarget.isDefaultCanvasTarget === true && parameters.context !== undefined ) {
  59332. context = parameters.context;
  59333. } else {
  59334. context = canvasTarget.domElement.getContext( 'webgpu' );
  59335. }
  59336. // OffscreenCanvas does not have setAttribute, see #22811
  59337. if ( 'setAttribute' in canvasTarget.domElement ) canvasTarget.domElement.setAttribute( 'data-engine', `three.js r${ REVISION } webgpu` );
  59338. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  59339. const toneMappingMode = parameters.outputType === HalfFloatType ? 'extended' : 'standard';
  59340. context.configure( {
  59341. device: this.device,
  59342. format: this.utils.getPreferredCanvasFormat(),
  59343. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  59344. alphaMode: alphaMode,
  59345. toneMapping: {
  59346. mode: toneMappingMode
  59347. }
  59348. } );
  59349. canvasData.context = context;
  59350. }
  59351. return context;
  59352. }
  59353. /**
  59354. * The coordinate system of the backend.
  59355. *
  59356. * @type {number}
  59357. * @readonly
  59358. */
  59359. get coordinateSystem() {
  59360. return WebGPUCoordinateSystem;
  59361. }
  59362. /**
  59363. * Whether the backend supports query timestamps or not.
  59364. *
  59365. * @type {boolean}
  59366. * @readonly
  59367. */
  59368. get hasTimestamp() {
  59369. return true;
  59370. }
  59371. /**
  59372. * This method performs a readback operation by moving buffer data from
  59373. * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can
  59374. * be used to retain and reuse handles to the intermediate buffers and prevent
  59375. * new allocation.
  59376. *
  59377. * @async
  59378. * @param {BufferAttribute} attribute - The storage buffer attribute to read frm.
  59379. * @param {number} count - The offset from which to start reading the
  59380. * @param {number} offset - The storage buffer attribute.
  59381. * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute.
  59382. * @return {Promise<ArrayBuffer|ReadbackBuffer>} A promise that resolves with the buffer data when the data are ready.
  59383. */
  59384. async getArrayBufferAsync( attribute, target = null, offset = 0, count = -1 ) {
  59385. return await this.attributeUtils.getArrayBufferAsync( attribute, target, offset, count );
  59386. }
  59387. /**
  59388. * Returns the backend's rendering context.
  59389. *
  59390. * @return {GPUCanvasContext} The rendering context.
  59391. */
  59392. getContext() {
  59393. return this.context;
  59394. }
  59395. /**
  59396. * Returns the default render pass descriptor.
  59397. *
  59398. * In WebGPU, the default framebuffer must be configured
  59399. * like custom framebuffers so the backend needs a render
  59400. * pass descriptor even when rendering directly to screen.
  59401. *
  59402. * @private
  59403. * @return {Object} The render pass descriptor.
  59404. */
  59405. _getDefaultRenderPassDescriptor() {
  59406. const renderer = this.renderer;
  59407. const canvasTarget = renderer.getCanvasTarget();
  59408. const canvasData = this.get( canvasTarget );
  59409. const samples = renderer.currentSamples;
  59410. let descriptor = canvasData.descriptor;
  59411. if ( descriptor === undefined || canvasData.samples !== samples ) {
  59412. descriptor = new GPURenderPassDescriptor();
  59413. descriptor.colorAttachments.push( new GPURenderPassColorAttachment() );
  59414. if ( renderer.depth === true || renderer.stencil === true ) {
  59415. const depthStencilAttachment = new GPURenderPassDepthStencilAttachment();
  59416. depthStencilAttachment.view = this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView();
  59417. descriptor.depthStencilAttachment = depthStencilAttachment;
  59418. }
  59419. const colorAttachment = descriptor.colorAttachments[ 0 ];
  59420. if ( samples > 0 ) {
  59421. colorAttachment.view = this.textureUtils.getColorBuffer().createView();
  59422. } else {
  59423. colorAttachment.resolveTarget = undefined;
  59424. }
  59425. canvasData.descriptor = descriptor;
  59426. canvasData.samples = samples;
  59427. }
  59428. const colorAttachment = descriptor.colorAttachments[ 0 ];
  59429. if ( samples > 0 ) {
  59430. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  59431. } else {
  59432. colorAttachment.view = this.context.getCurrentTexture().createView();
  59433. }
  59434. return descriptor;
  59435. }
  59436. /**
  59437. * Returns whether the render target is a render target array with depth 2D array texture.
  59438. *
  59439. * @param {RenderContext} renderContext - The render context.
  59440. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  59441. *
  59442. * @private
  59443. */
  59444. _isRenderCameraDepthArray( renderContext ) {
  59445. const camera = renderContext.camera;
  59446. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture === true && camera !== null && camera.isArrayCamera === true;
  59447. }
  59448. /**
  59449. * Returns whether the current render context references external textures.
  59450. *
  59451. * External textures can change every frame, so their descriptors must not be cached.
  59452. *
  59453. * @private
  59454. * @param {RenderContext} renderContext - The render context.
  59455. * @return {boolean} Whether the render context uses external textures.
  59456. */
  59457. _hasExternalTexture( renderContext ) {
  59458. const textures = renderContext.textures;
  59459. if ( textures === null ) return false;
  59460. for ( let i = 0; i < textures.length; i ++ ) {
  59461. if ( this.get( textures[ i ] ).externalTexture === true ) return true;
  59462. }
  59463. return false;
  59464. }
  59465. /**
  59466. * Creates attachment views for an external texture render target.
  59467. *
  59468. * @private
  59469. * @param {RenderContext} renderContext - The render context.
  59470. * @param {Object} textureData - The backend data for the texture.
  59471. * @return {Array<Object>} The attachment view descriptors.
  59472. */
  59473. _createExternalTextureViews( renderContext, textureData ) {
  59474. const textureViews = [];
  59475. const camera = renderContext.camera;
  59476. if ( textureData.xrViewDescriptors && camera !== null && camera.isArrayCamera === true ) {
  59477. for ( let i = 0; i < textureData.xrViewDescriptors.length; i ++ ) {
  59478. textureViews.push( {
  59479. view: textureData.texture.createView( textureData.xrViewDescriptors[ i ] ),
  59480. resolveTarget: undefined,
  59481. depthSlice: undefined
  59482. } );
  59483. }
  59484. } else {
  59485. textureViews.push( {
  59486. view: textureData.texture.createView( {
  59487. dimension: GPUTextureViewDimension.TwoD,
  59488. baseArrayLayer: renderContext.activeCubeFace,
  59489. arrayLayerCount: 1
  59490. } ),
  59491. resolveTarget: undefined,
  59492. depthSlice: undefined
  59493. } );
  59494. }
  59495. return textureViews;
  59496. }
  59497. /**
  59498. * Returns the render pass descriptor for the given render context.
  59499. *
  59500. * @private
  59501. * @param {RenderContext} renderContext - The render context.
  59502. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  59503. * @return {Object} The render pass descriptor.
  59504. */
  59505. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  59506. const renderTarget = renderContext.renderTarget;
  59507. const renderTargetData = this.get( renderTarget );
  59508. const hasExternalTexture = this._hasExternalTexture( renderContext );
  59509. let descriptors = renderTargetData.descriptors;
  59510. if ( descriptors === undefined ||
  59511. renderTargetData.width !== renderTarget.width ||
  59512. renderTargetData.height !== renderTarget.height ||
  59513. renderTargetData.samples !== renderTarget.samples ||
  59514. hasExternalTexture
  59515. ) {
  59516. descriptors = {};
  59517. renderTargetData.descriptors = descriptors;
  59518. }
  59519. const cacheKey = renderContext.getCacheKey();
  59520. let descriptorBase = descriptors[ cacheKey ];
  59521. if ( descriptorBase === undefined || hasExternalTexture ) {
  59522. const textures = renderContext.textures;
  59523. const textureViews = [];
  59524. let sliceIndex;
  59525. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  59526. for ( let i = 0; i < textures.length; i ++ ) {
  59527. const textureData = this.get( textures[ i ] );
  59528. if ( textureData.externalTexture === true ) {
  59529. textureViews.push( ...this._createExternalTextureViews( renderContext, textureData ) );
  59530. continue;
  59531. }
  59532. _viewDescriptor.label = `colorAttachment_${ i }`;
  59533. _viewDescriptor.baseMipLevel = renderContext.activeMipmapLevel;
  59534. _viewDescriptor.mipLevelCount = 1;
  59535. _viewDescriptor.baseArrayLayer = renderContext.activeCubeFace;
  59536. _viewDescriptor.arrayLayerCount = 1;
  59537. _viewDescriptor.dimension = GPUTextureViewDimension.TwoD;
  59538. if ( renderTarget.isRenderTarget3D ) {
  59539. sliceIndex = renderContext.activeCubeFace;
  59540. _viewDescriptor.baseArrayLayer = 0;
  59541. _viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  59542. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  59543. if ( isRenderCameraDepthArray === true ) {
  59544. const cameras = renderContext.camera.cameras;
  59545. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  59546. _viewDescriptor.baseArrayLayer = layer;
  59547. _viewDescriptor.arrayLayerCount = 1;
  59548. _viewDescriptor.dimension = GPUTextureViewDimension.TwoD;
  59549. const textureView = textureData.texture.createView( _viewDescriptor );
  59550. textureViews.push( {
  59551. view: textureView,
  59552. resolveTarget: undefined,
  59553. depthSlice: undefined
  59554. } );
  59555. }
  59556. } else {
  59557. _viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  59558. }
  59559. }
  59560. if ( isRenderCameraDepthArray !== true ) {
  59561. const textureView = textureData.texture.createView( _viewDescriptor );
  59562. let view, resolveTarget;
  59563. if ( textureData.msaaTexture !== undefined ) {
  59564. view = textureData.msaaTexture.createView();
  59565. resolveTarget = textureView;
  59566. } else {
  59567. view = textureView;
  59568. resolveTarget = undefined;
  59569. }
  59570. textureViews.push( {
  59571. view,
  59572. resolveTarget,
  59573. depthSlice: sliceIndex
  59574. } );
  59575. }
  59576. _viewDescriptor.reset();
  59577. }
  59578. const colorAttachments = [];
  59579. for ( let i = 0; i < textureViews.length; i ++ ) {
  59580. const viewInfo = textureViews[ i ];
  59581. const attachment = new GPURenderPassColorAttachment();
  59582. attachment.view = viewInfo.view;
  59583. attachment.depthSlice = viewInfo.depthSlice;
  59584. attachment.resolveTarget = viewInfo.resolveTarget;
  59585. colorAttachments.push( attachment );
  59586. }
  59587. descriptorBase = {
  59588. textureViews,
  59589. colorAttachments,
  59590. descriptor: new GPURenderPassDescriptor()
  59591. };
  59592. if ( renderContext.depth ) {
  59593. const depthTextureData = this.get( renderContext.depthTexture );
  59594. if ( renderContext.depthTexture.isArrayTexture || renderContext.depthTexture.isCubeTexture ) {
  59595. _viewDescriptor.dimension = GPUTextureViewDimension.TwoD;
  59596. _viewDescriptor.arrayLayerCount = 1;
  59597. _viewDescriptor.baseArrayLayer = renderContext.activeCubeFace;
  59598. }
  59599. const depthStencilAttachment = new GPURenderPassDepthStencilAttachment();
  59600. depthStencilAttachment.view = depthTextureData.texture.createView( _viewDescriptor );
  59601. descriptorBase.depthStencilAttachment = depthStencilAttachment;
  59602. _viewDescriptor.reset();
  59603. }
  59604. descriptors[ cacheKey ] = descriptorBase;
  59605. renderTargetData.width = renderTarget.width;
  59606. renderTargetData.height = renderTarget.height;
  59607. renderTargetData.samples = renderTarget.samples;
  59608. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  59609. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  59610. }
  59611. const descriptor = descriptorBase.descriptor;
  59612. descriptor.reset();
  59613. // Apply dynamic properties to cached attachments
  59614. for ( let i = 0; i < descriptorBase.colorAttachments.length; i ++ ) {
  59615. const attachment = descriptorBase.colorAttachments[ i ];
  59616. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  59617. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  59618. clearValue = colorAttachmentsConfig.clearValue;
  59619. }
  59620. attachment.loadOp = colorAttachmentsConfig.loadOp || GPULoadOp.Load;
  59621. attachment.storeOp = colorAttachmentsConfig.storeOp || GPUStoreOp.Store;
  59622. attachment.clearValue = clearValue;
  59623. descriptor.colorAttachments.push( attachment );
  59624. }
  59625. if ( descriptorBase.depthStencilAttachment ) {
  59626. descriptor.depthStencilAttachment = descriptorBase.depthStencilAttachment;
  59627. }
  59628. return descriptor;
  59629. }
  59630. /**
  59631. * This method is executed at the beginning of a render call and prepares
  59632. * the WebGPU state for upcoming render calls
  59633. *
  59634. * @param {RenderContext} renderContext - The render context.
  59635. */
  59636. beginRender( renderContext ) {
  59637. const renderContextData = this.get( renderContext );
  59638. //
  59639. const device = this.device;
  59640. const occlusionQueryCount = renderContext.occlusionQueryCount;
  59641. let occlusionQuerySet;
  59642. if ( occlusionQueryCount > 0 ) {
  59643. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  59644. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  59645. // Get a reference to the array of objects with queries. The renderContextData property
  59646. // can be changed by another render pass before the buffer.mapAsyc() completes.
  59647. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  59648. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  59649. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  59650. //
  59651. _querySetDescriptor.label = `occlusionQuerySet_${ renderContext.id }`;
  59652. _querySetDescriptor.type = 'occlusion';
  59653. _querySetDescriptor.count = occlusionQueryCount;
  59654. occlusionQuerySet = device.createQuerySet( _querySetDescriptor );
  59655. _querySetDescriptor.reset();
  59656. renderContextData.occlusionQuerySet = occlusionQuerySet;
  59657. renderContextData.occlusionQueryIndex = 0;
  59658. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  59659. renderContextData.lastOcclusionObject = null;
  59660. }
  59661. let descriptor;
  59662. if ( renderContext.textures === null ) {
  59663. descriptor = this._getDefaultRenderPassDescriptor();
  59664. } else {
  59665. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  59666. }
  59667. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  59668. descriptor.occlusionQuerySet = occlusionQuerySet;
  59669. const depthStencilAttachment = descriptor.depthStencilAttachment;
  59670. if ( renderContext.textures !== null ) {
  59671. const colorAttachments = descriptor.colorAttachments;
  59672. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  59673. const colorAttachment = colorAttachments[ i ];
  59674. if ( renderContext.clearColor ) {
  59675. if ( i === 0 ) {
  59676. colorAttachment.clearValue = renderContext.clearColorValue;
  59677. } else {
  59678. _clearValue.r = 0;
  59679. _clearValue.g = 0;
  59680. _clearValue.b = 0;
  59681. _clearValue.a = 1;
  59682. colorAttachment.clearValue = _clearValue;
  59683. }
  59684. colorAttachment.loadOp = GPULoadOp.Clear;
  59685. } else {
  59686. colorAttachment.loadOp = GPULoadOp.Load;
  59687. }
  59688. colorAttachment.storeOp = GPUStoreOp.Store;
  59689. }
  59690. } else {
  59691. const colorAttachment = descriptor.colorAttachments[ 0 ];
  59692. if ( renderContext.clearColor ) {
  59693. colorAttachment.clearValue = renderContext.clearColorValue;
  59694. colorAttachment.loadOp = GPULoadOp.Clear;
  59695. } else {
  59696. colorAttachment.loadOp = GPULoadOp.Load;
  59697. }
  59698. colorAttachment.storeOp = GPUStoreOp.Store;
  59699. }
  59700. //
  59701. if ( renderContext.depth ) {
  59702. if ( renderContext.clearDepth ) {
  59703. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  59704. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  59705. } else {
  59706. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  59707. }
  59708. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  59709. }
  59710. if ( renderContext.stencil ) {
  59711. if ( renderContext.clearStencil ) {
  59712. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  59713. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  59714. } else {
  59715. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  59716. }
  59717. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  59718. }
  59719. //
  59720. _commandEncoderDescriptor.label = 'renderContext_' + renderContext.id;
  59721. const encoder = device.createCommandEncoder( _commandEncoderDescriptor );
  59722. _commandEncoderDescriptor.reset();
  59723. // Layered render targets: prepare bundle encoders for each camera in the array camera.
  59724. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  59725. const cameras = renderContext.camera.cameras;
  59726. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  59727. this._createArrayCameraLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  59728. } else {
  59729. this._updateArrayCameraLayerDescriptors( renderContext, renderContextData, cameras );
  59730. }
  59731. // Create bundle encoders for each layer
  59732. renderContextData.bundleEncoders = [];
  59733. renderContextData.bundleSets = [];
  59734. // Create separate bundle encoders for each camera in the array
  59735. for ( let i = 0; i < cameras.length; i ++ ) {
  59736. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  59737. renderContext,
  59738. 'renderBundleArrayCamera_' + i
  59739. );
  59740. // Initialize state tracking for this bundle
  59741. const bundleSets = {
  59742. attributes: {},
  59743. bindingGroups: [],
  59744. pipeline: null,
  59745. index: null
  59746. };
  59747. renderContextData.bundleEncoders.push( bundleEncoder );
  59748. renderContextData.bundleSets.push( bundleSets );
  59749. }
  59750. // We'll complete the bundles in finishRender
  59751. renderContextData.currentPass = null;
  59752. } else {
  59753. const currentPass = encoder.beginRenderPass( descriptor );
  59754. renderContextData.currentPass = currentPass;
  59755. if ( renderContext.viewport ) {
  59756. this.updateViewport( renderContext );
  59757. }
  59758. if ( renderContext.scissor ) {
  59759. this.updateScissor( renderContext );
  59760. }
  59761. }
  59762. //
  59763. renderContextData.descriptor = descriptor;
  59764. renderContextData.encoder = encoder;
  59765. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  59766. renderContextData.renderBundles = [];
  59767. }
  59768. /**
  59769. * Creates render pass descriptors for each camera in an array camera.
  59770. *
  59771. * @param {RenderContext} renderContext - The render context.
  59772. * @param {Object} renderContextData - The render context data.
  59773. * @param {Object} descriptor - The render pass descriptor.
  59774. * @param {ArrayCamera} cameras - The array camera.
  59775. *
  59776. * @private
  59777. */
  59778. _createArrayCameraLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  59779. const depthStencilAttachment = descriptor.depthStencilAttachment;
  59780. renderContextData.layerDescriptors = [];
  59781. const depthTextureData = this.get( renderContext.depthTexture );
  59782. if ( ! depthTextureData.viewCache ) {
  59783. depthTextureData.viewCache = [];
  59784. }
  59785. for ( let i = 0; i < cameras.length; i ++ ) {
  59786. const sourceAttachment = descriptor.colorAttachments[ 0 ];
  59787. const layerColorAttachment = new GPURenderPassColorAttachment();
  59788. layerColorAttachment.view = descriptor.colorAttachments[ i ].view;
  59789. layerColorAttachment.depthSlice = sourceAttachment.depthSlice;
  59790. layerColorAttachment.resolveTarget = sourceAttachment.resolveTarget;
  59791. layerColorAttachment.loadOp = sourceAttachment.loadOp;
  59792. layerColorAttachment.storeOp = sourceAttachment.storeOp;
  59793. layerColorAttachment.clearValue = sourceAttachment.clearValue;
  59794. const layerDescriptor = new GPURenderPassDescriptor();
  59795. layerDescriptor.label = descriptor.label;
  59796. layerDescriptor.occlusionQuerySet = descriptor.occlusionQuerySet;
  59797. layerDescriptor.timestampWrites = descriptor.timestampWrites;
  59798. layerDescriptor.colorAttachments.push( layerColorAttachment );
  59799. if ( descriptor.depthStencilAttachment ) {
  59800. const layerIndex = i;
  59801. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  59802. _viewDescriptor.dimension = GPUTextureViewDimension.TwoD;
  59803. _viewDescriptor.baseArrayLayer = i;
  59804. _viewDescriptor.arrayLayerCount = 1;
  59805. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( _viewDescriptor );
  59806. _viewDescriptor.reset();
  59807. }
  59808. const layerDepthStencilAttachment = new GPURenderPassDepthStencilAttachment();
  59809. layerDepthStencilAttachment.view = depthTextureData.viewCache[ layerIndex ];
  59810. layerDepthStencilAttachment.depthLoadOp = depthStencilAttachment.depthLoadOp || GPULoadOp.Clear;
  59811. layerDepthStencilAttachment.depthStoreOp = depthStencilAttachment.depthStoreOp || GPUStoreOp.Store;
  59812. layerDepthStencilAttachment.depthClearValue = depthStencilAttachment.depthClearValue || 1.0;
  59813. if ( renderContext.stencil ) {
  59814. layerDepthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  59815. layerDepthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  59816. layerDepthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  59817. }
  59818. layerDescriptor.depthStencilAttachment = layerDepthStencilAttachment;
  59819. } else {
  59820. const layerDepthStencilAttachment = new GPURenderPassDepthStencilAttachment();
  59821. layerDepthStencilAttachment.view = depthStencilAttachment.view;
  59822. layerDepthStencilAttachment.depthLoadOp = depthStencilAttachment.depthLoadOp;
  59823. layerDepthStencilAttachment.depthStoreOp = depthStencilAttachment.depthStoreOp;
  59824. layerDepthStencilAttachment.depthClearValue = depthStencilAttachment.depthClearValue;
  59825. layerDepthStencilAttachment.depthReadOnly = depthStencilAttachment.depthReadOnly;
  59826. layerDepthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  59827. layerDepthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  59828. layerDepthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  59829. layerDepthStencilAttachment.stencilReadOnly = depthStencilAttachment.stencilReadOnly;
  59830. layerDescriptor.depthStencilAttachment = layerDepthStencilAttachment;
  59831. }
  59832. renderContextData.layerDescriptors.push( layerDescriptor );
  59833. }
  59834. }
  59835. /**
  59836. * Updates render pass descriptors for each camera in an array camera.
  59837. *
  59838. * @param {RenderContext} renderContext - The render context.
  59839. * @param {Object} renderContextData - The render context data.
  59840. * @param {ArrayCamera} cameras - The array camera.
  59841. *
  59842. */
  59843. _updateArrayCameraLayerDescriptors( renderContext, renderContextData, cameras ) {
  59844. for ( let i = 0; i < cameras.length; i ++ ) {
  59845. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  59846. if ( layerDescriptor.depthStencilAttachment ) {
  59847. const depthAttachment = layerDescriptor.depthStencilAttachment;
  59848. if ( renderContext.depth ) {
  59849. if ( renderContext.clearDepth ) {
  59850. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  59851. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  59852. } else {
  59853. depthAttachment.depthLoadOp = GPULoadOp.Load;
  59854. }
  59855. }
  59856. if ( renderContext.stencil ) {
  59857. if ( renderContext.clearStencil ) {
  59858. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  59859. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  59860. } else {
  59861. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  59862. }
  59863. }
  59864. }
  59865. }
  59866. }
  59867. /**
  59868. * This method is executed at the end of a render call and finalizes work
  59869. * after draw calls.
  59870. *
  59871. * @param {RenderContext} renderContext - The render context.
  59872. */
  59873. finishRender( renderContext ) {
  59874. const renderContextData = this.get( renderContext );
  59875. const occlusionQueryCount = renderContext.occlusionQueryCount;
  59876. if ( renderContextData.renderBundles.length > 0 ) {
  59877. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  59878. }
  59879. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  59880. renderContextData.currentPass.endOcclusionQuery();
  59881. }
  59882. // Layered render targets: execute the bundle for each layer.
  59883. const encoder = renderContextData.encoder;
  59884. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  59885. const bundles = [];
  59886. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  59887. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  59888. bundles.push( bundleEncoder.finish() );
  59889. }
  59890. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  59891. if ( i < bundles.length ) {
  59892. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  59893. const renderPass = encoder.beginRenderPass( layerDescriptor );
  59894. if ( renderContext.viewport ) {
  59895. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  59896. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  59897. }
  59898. if ( renderContext.scissor ) {
  59899. const { x, y, width, height } = renderContext.scissorValue;
  59900. renderPass.setScissorRect( x, y, width, height );
  59901. }
  59902. renderPass.executeBundles( [ bundles[ i ] ] );
  59903. renderPass.end();
  59904. }
  59905. }
  59906. } else if ( renderContextData.currentPass ) {
  59907. renderContextData.currentPass.end();
  59908. }
  59909. if ( occlusionQueryCount > 0 ) {
  59910. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  59911. //
  59912. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  59913. if ( queryResolveBuffer === undefined ) {
  59914. _bufferDescriptor.size = bufferSize;
  59915. _bufferDescriptor.usage = GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC;
  59916. queryResolveBuffer = this.device.createBuffer( _bufferDescriptor );
  59917. _bufferDescriptor.reset();
  59918. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  59919. }
  59920. //
  59921. _bufferDescriptor.size = bufferSize;
  59922. _bufferDescriptor.usage = GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ;
  59923. const readBuffer = this.device.createBuffer( _bufferDescriptor );
  59924. _bufferDescriptor.reset();
  59925. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  59926. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  59927. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  59928. renderContextData.occlusionQueryBuffer = readBuffer;
  59929. //
  59930. this.resolveOccludedAsync( renderContext );
  59931. }
  59932. submit( this.device, renderContextData.encoder.finish() );
  59933. //
  59934. if ( renderContext.textures !== null ) {
  59935. const textures = renderContext.textures;
  59936. for ( let i = 0; i < textures.length; i ++ ) {
  59937. const texture = textures[ i ];
  59938. if ( texture.generateMipmaps === true ) {
  59939. this.textureUtils.generateMipmaps( texture );
  59940. }
  59941. }
  59942. }
  59943. }
  59944. /**
  59945. * Returns `true` if the given 3D object is fully occluded by other
  59946. * 3D objects in the scene.
  59947. *
  59948. * @param {RenderContext} renderContext - The render context.
  59949. * @param {Object3D} object - The 3D object to test.
  59950. * @return {boolean} Whether the 3D object is fully occluded or not.
  59951. */
  59952. isOccluded( renderContext, object ) {
  59953. const renderContextData = this.get( renderContext );
  59954. return renderContextData.occluded && renderContextData.occluded.has( object );
  59955. }
  59956. /**
  59957. * This method processes the result of occlusion queries and writes it
  59958. * into render context data.
  59959. *
  59960. * @async
  59961. * @param {RenderContext} renderContext - The render context.
  59962. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  59963. */
  59964. async resolveOccludedAsync( renderContext ) {
  59965. const renderContextData = this.get( renderContext );
  59966. // handle occlusion query results
  59967. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  59968. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  59969. const occluded = new WeakSet();
  59970. renderContextData.currentOcclusionQueryObjects = null;
  59971. renderContextData.currentOcclusionQueryBuffer = null;
  59972. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  59973. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  59974. const results = new BigUint64Array( buffer );
  59975. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  59976. if ( results[ i ] === BigInt( 0 ) ) {
  59977. occluded.add( currentOcclusionQueryObjects[ i ] );
  59978. }
  59979. }
  59980. currentOcclusionQueryBuffer.destroy();
  59981. renderContextData.occluded = occluded;
  59982. }
  59983. }
  59984. /**
  59985. * Updates the viewport with the values from the given render context.
  59986. *
  59987. * @param {RenderContext} renderContext - The render context.
  59988. */
  59989. updateViewport( renderContext ) {
  59990. const { currentPass } = this.get( renderContext );
  59991. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  59992. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  59993. }
  59994. /**
  59995. * Updates the scissor with the values from the given render context.
  59996. *
  59997. * @param {RenderContext} renderContext - The render context.
  59998. */
  59999. updateScissor( renderContext ) {
  60000. const { currentPass } = this.get( renderContext );
  60001. const { x, y, width, height } = renderContext.scissorValue;
  60002. currentPass.setScissorRect( x, y, width, height );
  60003. }
  60004. /**
  60005. * Returns the clear color and alpha into a single
  60006. * color object.
  60007. *
  60008. * @return {Color4} The clear color.
  60009. */
  60010. getClearColor() {
  60011. const clearColor = super.getClearColor();
  60012. // only premultiply alpha when alphaMode is "premultiplied"
  60013. if ( this.renderer.alpha === true ) {
  60014. clearColor.r *= clearColor.a;
  60015. clearColor.g *= clearColor.a;
  60016. clearColor.b *= clearColor.a;
  60017. }
  60018. return clearColor;
  60019. }
  60020. /**
  60021. * Performs a clear operation.
  60022. *
  60023. * @param {boolean} color - Whether the color buffer should be cleared or not.
  60024. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  60025. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  60026. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  60027. */
  60028. clear( color, depth, stencil, renderTargetContext = null ) {
  60029. const device = this.device;
  60030. const renderer = this.renderer;
  60031. let colorAttachments = [];
  60032. let depthStencilAttachment;
  60033. let supportsDepth;
  60034. let supportsStencil;
  60035. if ( color ) {
  60036. const clearColor = this.getClearColor();
  60037. _clearValue.r = clearColor.r;
  60038. _clearValue.g = clearColor.g;
  60039. _clearValue.b = clearColor.b;
  60040. _clearValue.a = clearColor.a;
  60041. }
  60042. if ( renderTargetContext === null ) {
  60043. supportsDepth = renderer.depth;
  60044. supportsStencil = renderer.stencil;
  60045. const descriptor = this._getDefaultRenderPassDescriptor();
  60046. if ( color ) {
  60047. colorAttachments = descriptor.colorAttachments;
  60048. const colorAttachment = colorAttachments[ 0 ];
  60049. colorAttachment.clearValue = _clearValue;
  60050. colorAttachment.loadOp = GPULoadOp.Clear;
  60051. colorAttachment.storeOp = GPUStoreOp.Store;
  60052. }
  60053. if ( supportsDepth || supportsStencil ) {
  60054. depthStencilAttachment = descriptor.depthStencilAttachment;
  60055. }
  60056. } else {
  60057. supportsDepth = renderTargetContext.depth;
  60058. supportsStencil = renderTargetContext.stencil;
  60059. const clearConfig = {
  60060. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  60061. clearValue: color ? _clearValue : undefined
  60062. };
  60063. if ( supportsDepth ) {
  60064. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  60065. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  60066. clearConfig.depthStoreOp = GPUStoreOp.Store;
  60067. }
  60068. if ( supportsStencil ) {
  60069. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  60070. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  60071. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  60072. }
  60073. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  60074. colorAttachments = descriptor.colorAttachments;
  60075. depthStencilAttachment = descriptor.depthStencilAttachment;
  60076. }
  60077. if ( supportsDepth && depthStencilAttachment ) {
  60078. if ( depth ) {
  60079. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  60080. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  60081. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  60082. } else {
  60083. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  60084. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  60085. }
  60086. }
  60087. //
  60088. if ( supportsStencil && depthStencilAttachment ) {
  60089. if ( stencil ) {
  60090. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  60091. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  60092. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  60093. } else {
  60094. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  60095. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  60096. }
  60097. }
  60098. //
  60099. _commandEncoderDescriptor.label = 'clear';
  60100. const encoder = device.createCommandEncoder( _commandEncoderDescriptor );
  60101. _commandEncoderDescriptor.reset();
  60102. const currentPass = encoder.beginRenderPass( {
  60103. colorAttachments,
  60104. depthStencilAttachment
  60105. } );
  60106. currentPass.end();
  60107. submit( device, encoder.finish() );
  60108. }
  60109. // compute
  60110. /**
  60111. * This method is executed at the beginning of a compute call and
  60112. * prepares the state for upcoming compute tasks.
  60113. *
  60114. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  60115. */
  60116. beginCompute( computeGroup ) {
  60117. const groupGPU = this.get( computeGroup );
  60118. //
  60119. const label = 'computeGroup_' + computeGroup.id;
  60120. _computePassDescriptor.label = label;
  60121. _commandEncoderDescriptor.label = label;
  60122. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), _computePassDescriptor );
  60123. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( _commandEncoderDescriptor );
  60124. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( _computePassDescriptor );
  60125. groupGPU.currentPipeline = null;
  60126. _commandEncoderDescriptor.reset();
  60127. _computePassDescriptor.reset();
  60128. }
  60129. /**
  60130. * Executes a compute command for the given compute node.
  60131. *
  60132. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  60133. * @param {Node} computeNode - The compute node.
  60134. * @param {Array<BindGroup>} bindings - The bindings.
  60135. * @param {ComputePipeline} pipeline - The compute pipeline.
  60136. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  60137. * - A single number representing count, or
  60138. * - An array [x, y, z] representing dispatch size, or
  60139. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  60140. */
  60141. compute( computeGroup, computeNode, bindings, pipeline, dispatchSize = null ) {
  60142. const computeNodeData = this.get( computeNode );
  60143. const groupGPU = this.get( computeGroup );
  60144. const { passEncoderGPU } = groupGPU;
  60145. // pipeline
  60146. const pipelineGPU = this.get( pipeline ).pipeline;
  60147. if ( groupGPU.currentPipeline !== pipelineGPU ) {
  60148. passEncoderGPU.setPipeline( pipelineGPU );
  60149. groupGPU.currentPipeline = pipelineGPU;
  60150. }
  60151. // bind groups
  60152. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  60153. const bindGroup = bindings[ i ];
  60154. const bindingsData = this.get( bindGroup );
  60155. passEncoderGPU.setBindGroup( i, bindingsData.group );
  60156. }
  60157. if ( dispatchSize === null ) {
  60158. dispatchSize = computeNode.dispatchSize || computeNode.count;
  60159. }
  60160. // When the dispatchSize is set with a StorageBuffer from the GPU.
  60161. if ( dispatchSize && dispatchSize.isIndirectStorageBufferAttribute ) {
  60162. const dispatchBuffer = this.get( dispatchSize ).buffer;
  60163. passEncoderGPU.dispatchWorkgroupsIndirect( dispatchBuffer, 0 );
  60164. return;
  60165. }
  60166. if ( typeof dispatchSize === 'number' ) {
  60167. // If a single number is given, we calculate the dispatch size based on the workgroup size
  60168. const count = dispatchSize;
  60169. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  60170. // cache dispatch size to avoid recalculating it every time
  60171. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  60172. computeNodeData.count = count;
  60173. const workgroupSize = computeNode.workgroupSize;
  60174. let size = workgroupSize[ 0 ];
  60175. for ( let i = 1; i < workgroupSize.length; i ++ )
  60176. size *= workgroupSize[ i ];
  60177. const dispatchCount = Math.ceil( count / size );
  60178. //
  60179. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  60180. dispatchSize = [ dispatchCount, 1, 1 ];
  60181. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  60182. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  60183. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  60184. }
  60185. computeNodeData.dispatchSize = dispatchSize;
  60186. }
  60187. dispatchSize = computeNodeData.dispatchSize;
  60188. }
  60189. //
  60190. passEncoderGPU.dispatchWorkgroups(
  60191. dispatchSize[ 0 ],
  60192. dispatchSize[ 1 ] || 1,
  60193. dispatchSize[ 2 ] || 1
  60194. );
  60195. }
  60196. /**
  60197. * This method is executed at the end of a compute call and
  60198. * finalizes work after compute tasks.
  60199. *
  60200. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  60201. */
  60202. finishCompute( computeGroup ) {
  60203. const groupData = this.get( computeGroup );
  60204. groupData.passEncoderGPU.end();
  60205. submit( this.device, groupData.cmdEncoderGPU.finish() );
  60206. }
  60207. /**
  60208. * Internal draw function that performs the draw with the given pass encoder.
  60209. *
  60210. * @private
  60211. * @param {RenderObject} renderObject - The render object.
  60212. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  60213. * @param {Object} renderContextData - The render context data object, holding current pass state and occlusion query tracking.
  60214. * @param {GPURenderPipeline} pipelineGPU - The GPU render pipeline.
  60215. * @param {Array<BindGroup>} bindings - The bind groups.
  60216. * @param {Array<BufferAttribute>} vertexBuffers - The vertex buffers.
  60217. * @param {{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} drawParams - The draw parameters.
  60218. * @param {GPURenderPassEncoder|GPURenderBundleEncoder} passEncoderGPU - The GPU pass encoder used for recording draw commands.
  60219. * @param {Object} currentSets - Tracking object for currently set pipeline, attributes, bind groups, and index state.
  60220. */
  60221. _draw( renderObject, info, renderContextData, pipelineGPU, bindings, vertexBuffers, drawParams, passEncoderGPU, currentSets ) {
  60222. const { object, material, context } = renderObject;
  60223. const index = renderObject.getIndex();
  60224. const hasIndex = ( index !== null );
  60225. // pipeline
  60226. if ( currentSets.pipeline !== pipelineGPU ) {
  60227. passEncoderGPU.setPipeline( pipelineGPU );
  60228. currentSets.pipeline = pipelineGPU;
  60229. }
  60230. // bind groups
  60231. const currentBindingGroups = currentSets.bindingGroups;
  60232. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  60233. const bindGroup = bindings[ i ];
  60234. if ( currentBindingGroups[ i ] !== bindGroup.id ) {
  60235. const bindingsData = this.get( bindGroup );
  60236. passEncoderGPU.setBindGroup( i, bindingsData.group );
  60237. currentBindingGroups[ i ] = bindGroup.id;
  60238. }
  60239. }
  60240. // attributes
  60241. // index
  60242. if ( hasIndex === true ) {
  60243. if ( currentSets.index !== index ) {
  60244. const buffer = this.get( index ).buffer;
  60245. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  60246. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  60247. currentSets.index = index;
  60248. }
  60249. }
  60250. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  60251. const vertexBuffer = vertexBuffers[ i ];
  60252. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  60253. const buffer = this.get( vertexBuffer ).buffer;
  60254. passEncoderGPU.setVertexBuffer( i, buffer );
  60255. currentSets.attributes[ i ] = vertexBuffer;
  60256. }
  60257. }
  60258. // stencil
  60259. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  60260. passEncoderGPU.setStencilReference( material.stencilRef );
  60261. renderContextData.currentStencilRef = material.stencilRef;
  60262. }
  60263. if ( object.isBatchedMesh === true ) {
  60264. const starts = object._multiDrawStarts;
  60265. const counts = object._multiDrawCounts;
  60266. const drawCount = object._multiDrawCount;
  60267. let bytesPerElement = ( hasIndex === true ) ? index.array.BYTES_PER_ELEMENT : 1;
  60268. if ( material.wireframe ) {
  60269. bytesPerElement = object.geometry.attributes.position.count > 65535 ? 4 : 2;
  60270. }
  60271. for ( let i = 0; i < drawCount; i ++ ) {
  60272. if ( hasIndex === true ) {
  60273. passEncoderGPU.drawIndexed( counts[ i ], 1, starts[ i ] / bytesPerElement, 0, i );
  60274. } else {
  60275. passEncoderGPU.draw( counts[ i ], 1, starts[ i ], i );
  60276. }
  60277. info.update( object, counts[ i ], 1 );
  60278. }
  60279. } else if ( hasIndex === true ) {
  60280. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  60281. const indirect = renderObject.getIndirect();
  60282. if ( indirect !== null ) {
  60283. const buffer = this.get( indirect ).buffer;
  60284. const indirectOffset = renderObject.getIndirectOffset();
  60285. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  60286. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  60287. passEncoderGPU.drawIndexedIndirect( buffer, indirectOffsets[ i ] );
  60288. }
  60289. } else {
  60290. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  60291. }
  60292. info.update( object, indexCount, instanceCount );
  60293. } else {
  60294. const { vertexCount, instanceCount, firstVertex } = drawParams;
  60295. const indirect = renderObject.getIndirect();
  60296. if ( indirect !== null ) {
  60297. const buffer = this.get( indirect ).buffer;
  60298. const indirectOffset = renderObject.getIndirectOffset();
  60299. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  60300. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  60301. passEncoderGPU.drawIndirect( buffer, indirectOffsets[ i ] );
  60302. }
  60303. } else {
  60304. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  60305. }
  60306. info.update( object, vertexCount, instanceCount );
  60307. }
  60308. }
  60309. // render object
  60310. /**
  60311. * Executes a draw command for the given render object.
  60312. *
  60313. * @param {RenderObject} renderObject - The render object to draw.
  60314. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  60315. */
  60316. draw( renderObject, info ) {
  60317. const { object, context, pipeline } = renderObject;
  60318. const renderContextData = this.get( context );
  60319. const pipelineData = this.get( pipeline );
  60320. const pipelineGPU = pipelineData.pipeline;
  60321. // Skip if pipeline has error
  60322. if ( pipelineData.error === true ) return;
  60323. const drawParams = renderObject.getDrawParameters();
  60324. if ( drawParams === null ) return;
  60325. const bindings = renderObject.getBindings();
  60326. // vertex buffers
  60327. const vertexBuffers = renderObject.getVertexBuffers();
  60328. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  60329. const cameraData = this.get( renderObject.camera );
  60330. const cameras = renderObject.camera.cameras;
  60331. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  60332. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  60333. const bindingsData = this.get( cameraIndex );
  60334. const indexesGPU = [];
  60335. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  60336. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  60337. data[ 0 ] = i;
  60338. const { layoutGPU } = bindingsData.layout;
  60339. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, layoutGPU );
  60340. indexesGPU.push( bindGroupIndex );
  60341. }
  60342. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  60343. }
  60344. const pixelRatio = this.renderer.getPixelRatio();
  60345. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  60346. const subCamera = cameras[ i ];
  60347. if ( object.layers.test( subCamera.layers ) ) {
  60348. const vp = subCamera.viewport;
  60349. let pass = renderContextData.currentPass;
  60350. let sets = renderContextData.currentSets;
  60351. const isBundleEncoder = renderContextData.bundleEncoders !== undefined;
  60352. if ( isBundleEncoder ) {
  60353. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  60354. const bundleSets = renderContextData.bundleSets[ i ];
  60355. pass = bundleEncoder;
  60356. sets = bundleSets;
  60357. }
  60358. // GPURenderBundleEncoder does not support setViewport, only GPURenderPassEncoder does
  60359. if ( vp && ! isBundleEncoder ) {
  60360. pass.setViewport(
  60361. Math.floor( vp.x * pixelRatio ),
  60362. Math.floor( vp.y * pixelRatio ),
  60363. Math.floor( vp.width * pixelRatio ),
  60364. Math.floor( vp.height * pixelRatio ),
  60365. context.viewportValue.minDepth,
  60366. context.viewportValue.maxDepth
  60367. );
  60368. }
  60369. // Set camera index binding for this layer
  60370. if ( cameraIndex && cameraData.indexesGPU ) {
  60371. const indexPos = bindings.indexOf( cameraIndex );
  60372. pass.setBindGroup( indexPos, cameraData.indexesGPU[ i ] );
  60373. sets.bindingGroups[ indexPos ] = cameraIndex.id;
  60374. }
  60375. this._draw( renderObject, info, renderContextData, pipelineGPU, bindings, vertexBuffers, drawParams, pass, sets );
  60376. }
  60377. }
  60378. } else {
  60379. // Regular single camera rendering
  60380. if ( renderContextData.currentPass ) {
  60381. // Handle occlusion queries
  60382. if ( renderContextData.occlusionQuerySet !== undefined ) {
  60383. const lastObject = renderContextData.lastOcclusionObject;
  60384. if ( lastObject !== object ) {
  60385. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  60386. renderContextData.currentPass.endOcclusionQuery();
  60387. renderContextData.occlusionQueryIndex ++;
  60388. }
  60389. if ( object.occlusionTest === true ) {
  60390. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  60391. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  60392. }
  60393. renderContextData.lastOcclusionObject = object;
  60394. }
  60395. }
  60396. this._draw( renderObject, info, renderContextData, pipelineGPU, bindings, vertexBuffers, drawParams, renderContextData.currentPass, renderContextData.currentSets );
  60397. }
  60398. }
  60399. }
  60400. // cache key
  60401. /**
  60402. * Returns `true` if the render pipeline requires an update.
  60403. *
  60404. * @param {RenderObject} renderObject - The render object.
  60405. * @return {boolean} Whether the render pipeline requires an update or not.
  60406. */
  60407. needsRenderUpdate( renderObject ) {
  60408. const data = this.get( renderObject );
  60409. const { object, material } = renderObject;
  60410. const utils = this.utils;
  60411. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  60412. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  60413. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  60414. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  60415. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  60416. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  60417. let needsUpdate = false;
  60418. if ( data.material !== material || data.materialVersion !== material.version ||
  60419. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  60420. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  60421. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  60422. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  60423. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  60424. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  60425. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  60426. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  60427. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  60428. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  60429. data.primitiveTopology !== primitiveTopology ||
  60430. data.frontFaceCW !== frontFaceCW ||
  60431. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  60432. ) {
  60433. data.material = material; data.materialVersion = material.version;
  60434. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  60435. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  60436. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  60437. data.colorWrite = material.colorWrite;
  60438. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  60439. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  60440. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  60441. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  60442. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  60443. data.sampleCount = sampleCount;
  60444. data.colorSpace = colorSpace;
  60445. data.colorFormat = colorFormat;
  60446. data.depthStencilFormat = depthStencilFormat;
  60447. data.primitiveTopology = primitiveTopology;
  60448. data.frontFaceCW = frontFaceCW;
  60449. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  60450. needsUpdate = true;
  60451. }
  60452. return needsUpdate;
  60453. }
  60454. /**
  60455. * Returns a cache key that is used to identify render pipelines.
  60456. *
  60457. * @param {RenderObject} renderObject - The render object.
  60458. * @return {string} The cache key.
  60459. */
  60460. getRenderCacheKey( renderObject ) {
  60461. const { object, material } = renderObject;
  60462. const utils = this.utils;
  60463. const renderContext = renderObject.context;
  60464. // meshes with negative scale have a different frontFace render pipeline
  60465. // descriptor value so the following must be honored in the cache key
  60466. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  60467. return [
  60468. material.transparent, material.blending, material.premultipliedAlpha,
  60469. material.blendSrc, material.blendDst, material.blendEquation,
  60470. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  60471. material.colorWrite,
  60472. material.depthWrite, material.depthTest, material.depthFunc,
  60473. material.stencilWrite, material.stencilFunc,
  60474. material.stencilFail, material.stencilZFail, material.stencilZPass,
  60475. material.stencilFuncMask, material.stencilWriteMask,
  60476. material.side,
  60477. frontFaceCW,
  60478. utils.getSampleCountRenderContext( renderContext ),
  60479. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  60480. utils.getPrimitiveTopology( object, material ),
  60481. renderObject.getGeometryCacheKey(),
  60482. renderObject.clippingContextCacheKey
  60483. ].join();
  60484. }
  60485. // textures
  60486. /**
  60487. * Updates a GPU sampler for the given texture.
  60488. *
  60489. * @param {Texture} texture - The texture to update the sampler for.
  60490. * @param {TextureNode} textureNode - The texture node to update the sampler with.
  60491. * @return {string} The current sampler key.
  60492. */
  60493. updateSampler( texture, textureNode ) {
  60494. return this.textureUtils.updateSampler( texture, textureNode );
  60495. }
  60496. /**
  60497. * Creates a default texture for the given texture that can be used
  60498. * as a placeholder until the actual texture is ready for usage.
  60499. *
  60500. * @param {Texture} texture - The texture to create a default texture for.
  60501. * @return {boolean} Whether the sampler has been updated or not.
  60502. */
  60503. createDefaultTexture( texture ) {
  60504. return this.textureUtils.createDefaultTexture( texture );
  60505. }
  60506. /**
  60507. * Defines a texture on the GPU for the given texture object.
  60508. *
  60509. * @param {Texture} texture - The texture.
  60510. * @param {Object} [options={}] - Optional configuration parameter.
  60511. */
  60512. createTexture( texture, options ) {
  60513. this.textureUtils.createTexture( texture, options );
  60514. }
  60515. /**
  60516. * Uploads the updated texture data to the GPU.
  60517. *
  60518. * @param {Texture} texture - The texture.
  60519. * @param {Object} [options={}] - Optional configuration parameter.
  60520. */
  60521. updateTexture( texture, options ) {
  60522. this.textureUtils.updateTexture( texture, options );
  60523. }
  60524. /**
  60525. * Generates mipmaps for the given texture.
  60526. *
  60527. * @param {Texture} texture - The texture.
  60528. */
  60529. generateMipmaps( texture ) {
  60530. this.textureUtils.generateMipmaps( texture );
  60531. }
  60532. /**
  60533. * Destroys the GPU data for the given texture object.
  60534. *
  60535. * @param {Texture} texture - The texture.
  60536. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  60537. */
  60538. destroyTexture( texture, isDefaultTexture = false ) {
  60539. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  60540. }
  60541. /**
  60542. * Returns texture data as a typed array.
  60543. *
  60544. * @async
  60545. * @param {Texture} texture - The texture to copy.
  60546. * @param {number} x - The x coordinate of the copy origin.
  60547. * @param {number} y - The y coordinate of the copy origin.
  60548. * @param {number} width - The width of the copy.
  60549. * @param {number} height - The height of the copy.
  60550. * @param {number} faceIndex - The face index.
  60551. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  60552. */
  60553. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  60554. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  60555. }
  60556. /**
  60557. * Inits a time stamp query for the given render context.
  60558. *
  60559. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  60560. * @param {number} uid - Unique id for the context (e.g. render context id).
  60561. * @param {Object} descriptor - The query descriptor.
  60562. */
  60563. initTimestampQuery( type, uid, descriptor ) {
  60564. if ( ! this.trackTimestamp ) return;
  60565. if ( ! this.timestampQueryPool[ type ] ) {
  60566. // TODO: Variable maxQueries?
  60567. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  60568. }
  60569. const timestampQueryPool = this.timestampQueryPool[ type ];
  60570. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  60571. _renderPassTimestampWrites.querySet = timestampQueryPool.querySet;
  60572. _renderPassTimestampWrites.beginningOfPassWriteIndex = baseOffset;
  60573. _renderPassTimestampWrites.endOfPassWriteIndex = baseOffset + 1;
  60574. descriptor.timestampWrites = _renderPassTimestampWrites;
  60575. }
  60576. // node builder
  60577. /**
  60578. * Returns a node builder for the given render object.
  60579. *
  60580. * @param {RenderObject} object - The render object.
  60581. * @param {Renderer} renderer - The renderer.
  60582. * @return {WGSLNodeBuilder} The node builder.
  60583. */
  60584. createNodeBuilder( object, renderer ) {
  60585. return new WGSLNodeBuilder( object, renderer );
  60586. }
  60587. // program
  60588. /**
  60589. * Creates a shader program from the given programmable stage.
  60590. *
  60591. * @param {ProgrammableStage} program - The programmable stage.
  60592. */
  60593. createProgram( program ) {
  60594. const programGPU = this.get( program );
  60595. _shaderModuleDescriptor.label = program.stage + ( program.name !== '' ? `_${ program.name }` : '' );
  60596. _shaderModuleDescriptor.code = program.code;
  60597. programGPU.module = {
  60598. module: this.device.createShaderModule( _shaderModuleDescriptor ),
  60599. entryPoint: 'main'
  60600. };
  60601. _shaderModuleDescriptor.reset();
  60602. }
  60603. /**
  60604. * Destroys the shader program of the given programmable stage.
  60605. *
  60606. * @param {ProgrammableStage} program - The programmable stage.
  60607. */
  60608. destroyProgram( program ) {
  60609. this.delete( program );
  60610. }
  60611. // pipelines
  60612. /**
  60613. * Creates a render pipeline for the given render object.
  60614. *
  60615. * @param {RenderObject} renderObject - The render object.
  60616. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  60617. */
  60618. createRenderPipeline( renderObject, promises ) {
  60619. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  60620. }
  60621. /**
  60622. * Creates a compute pipeline for the given compute node.
  60623. *
  60624. * @param {ComputePipeline} computePipeline - The compute pipeline.
  60625. * @param {Array<BindGroup>} bindings - The bindings.
  60626. */
  60627. createComputePipeline( computePipeline, bindings ) {
  60628. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  60629. }
  60630. /**
  60631. * Prepares the state for encoding render bundles.
  60632. *
  60633. * @param {RenderContext} renderContext - The render context.
  60634. */
  60635. beginBundle( renderContext ) {
  60636. const renderContextData = this.get( renderContext );
  60637. renderContextData._currentPass = renderContextData.currentPass;
  60638. renderContextData._currentSets = renderContextData.currentSets;
  60639. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  60640. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  60641. }
  60642. /**
  60643. * After processing render bundles this method finalizes related work.
  60644. *
  60645. * @param {RenderContext} renderContext - The render context.
  60646. * @param {RenderBundle} bundle - The render bundle.
  60647. */
  60648. finishBundle( renderContext, bundle ) {
  60649. const renderContextData = this.get( renderContext );
  60650. const bundleEncoder = renderContextData.currentPass;
  60651. const bundleGPU = bundleEncoder.finish();
  60652. this.get( bundle ).bundleGPU = bundleGPU;
  60653. // restore render pass state
  60654. renderContextData.currentSets = renderContextData._currentSets;
  60655. renderContextData.currentPass = renderContextData._currentPass;
  60656. }
  60657. /**
  60658. * Adds a render bundle to the render context data.
  60659. *
  60660. * @param {RenderContext} renderContext - The render context.
  60661. * @param {RenderBundle} bundle - The render bundle to add.
  60662. */
  60663. addBundle( renderContext, bundle ) {
  60664. const renderContextData = this.get( renderContext );
  60665. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  60666. }
  60667. // bindings
  60668. /**
  60669. * Creates a uniform buffer.
  60670. *
  60671. * @param {Buffer} uniformBuffer - The uniform buffer.
  60672. */
  60673. createUniformBuffer( uniformBuffer ) {
  60674. const uniformBufferData = this.get( uniformBuffer );
  60675. if ( uniformBufferData.buffer === undefined ) {
  60676. const byteLength = uniformBuffer.byteLength;
  60677. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  60678. const visibilities = [];
  60679. if ( uniformBuffer.visibility & GPUShaderStage.VERTEX ) {
  60680. visibilities.push( 'vertex' );
  60681. }
  60682. if ( uniformBuffer.visibility & GPUShaderStage.FRAGMENT ) {
  60683. visibilities.push( 'fragment' );
  60684. }
  60685. if ( uniformBuffer.visibility & GPUShaderStage.COMPUTE ) {
  60686. visibilities.push( 'compute' );
  60687. }
  60688. const bufferVisibility = `(${visibilities.join( ',' )})`;
  60689. _bufferDescriptor.label = `bindingBuffer${uniformBuffer.id}_${uniformBuffer.name}_${bufferVisibility}`;
  60690. _bufferDescriptor.size = byteLength;
  60691. _bufferDescriptor.usage = usage;
  60692. const bufferGPU = this.device.createBuffer( _bufferDescriptor );
  60693. _bufferDescriptor.reset();
  60694. uniformBufferData.buffer = bufferGPU;
  60695. }
  60696. }
  60697. /**
  60698. * Destroys the GPU data for the given uniform buffer.
  60699. *
  60700. * @param {Buffer} uniformBuffer - The uniform buffer.
  60701. */
  60702. destroyUniformBuffer( uniformBuffer ) {
  60703. const uniformBufferData = this.get( uniformBuffer );
  60704. uniformBufferData.buffer.destroy();
  60705. this.delete( uniformBuffer );
  60706. }
  60707. /**
  60708. * Creates bindings from the given bind group definition.
  60709. *
  60710. * @param {BindGroup} bindGroup - The bind group.
  60711. * @param {Array<BindGroup>} bindings - Array of bind groups.
  60712. * @param {number} cacheIndex - The cache index.
  60713. * @param {number} version - The version.
  60714. */
  60715. createBindings( bindGroup, bindings, cacheIndex, version ) {
  60716. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  60717. }
  60718. /**
  60719. * Updates the given bind group definition.
  60720. *
  60721. * @param {BindGroup} bindGroup - The bind group.
  60722. * @param {Array<BindGroup>} bindings - Array of bind groups.
  60723. * @param {number} cacheIndex - The cache index.
  60724. * @param {number} version - The version.
  60725. */
  60726. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  60727. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  60728. }
  60729. /**
  60730. * Updates a buffer binding.
  60731. *
  60732. * @param {Buffer} binding - The buffer binding to update.
  60733. */
  60734. updateBinding( binding ) {
  60735. this.bindingUtils.updateBinding( binding );
  60736. }
  60737. /**
  60738. * Delete data associated with the current bind group.
  60739. *
  60740. * @param {BindGroup} bindGroup - The bind group.
  60741. */
  60742. deleteBindGroupData( bindGroup ) {
  60743. this.bindingUtils.deleteBindGroupData( bindGroup );
  60744. }
  60745. // attributes
  60746. /**
  60747. * Creates the buffer of an indexed shader attribute.
  60748. *
  60749. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  60750. */
  60751. createIndexAttribute( attribute ) {
  60752. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  60753. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  60754. usage |= GPUBufferUsage.STORAGE;
  60755. }
  60756. this.attributeUtils.createAttribute( attribute, usage );
  60757. }
  60758. /**
  60759. * Creates the GPU buffer of a shader attribute.
  60760. *
  60761. * @param {BufferAttribute} attribute - The buffer attribute.
  60762. */
  60763. createAttribute( attribute ) {
  60764. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  60765. }
  60766. /**
  60767. * Creates the GPU buffer of a storage attribute.
  60768. *
  60769. * @param {BufferAttribute} attribute - The buffer attribute.
  60770. */
  60771. createStorageAttribute( attribute ) {
  60772. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  60773. }
  60774. /**
  60775. * Creates the GPU buffer of an indirect storage attribute.
  60776. *
  60777. * @param {BufferAttribute} attribute - The buffer attribute.
  60778. */
  60779. createIndirectStorageAttribute( attribute ) {
  60780. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  60781. }
  60782. /**
  60783. * Updates the GPU buffer of a shader attribute.
  60784. *
  60785. * @param {BufferAttribute} attribute - The buffer attribute to update.
  60786. */
  60787. updateAttribute( attribute ) {
  60788. this.attributeUtils.updateAttribute( attribute );
  60789. }
  60790. /**
  60791. * Destroys the GPU buffer of a shader attribute.
  60792. *
  60793. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  60794. */
  60795. destroyAttribute( attribute ) {
  60796. this.attributeUtils.destroyAttribute( attribute );
  60797. }
  60798. // canvas
  60799. /**
  60800. * Triggers an update of the default render pass descriptor.
  60801. */
  60802. updateSize() {
  60803. this.delete( this.renderer.getCanvasTarget() );
  60804. }
  60805. // utils public
  60806. /**
  60807. * Checks if the given feature is supported by the backend.
  60808. *
  60809. * @param {string} name - The feature's name.
  60810. * @return {boolean} Whether the feature is supported or not.
  60811. */
  60812. hasFeature( name ) {
  60813. if ( GPUFeatureMap[ name ] !== undefined ) name = GPUFeatureMap[ name ];
  60814. return this.device.features.has( name );
  60815. }
  60816. /**
  60817. * Copies data of the given source texture to the given destination texture.
  60818. *
  60819. * @param {Texture} srcTexture - The source texture.
  60820. * @param {Texture} dstTexture - The destination texture.
  60821. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  60822. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  60823. * @param {number} [srcLevel=0] - The mipmap level to copy.
  60824. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  60825. */
  60826. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  60827. let dstX = 0;
  60828. let dstY = 0;
  60829. let dstZ = 0;
  60830. let srcX = 0;
  60831. let srcY = 0;
  60832. let srcZ = 0;
  60833. let srcWidth = srcTexture.image.width;
  60834. let srcHeight = srcTexture.image.height;
  60835. let srcDepth = 1;
  60836. if ( srcRegion !== null ) {
  60837. if ( srcRegion.isBox3 === true ) {
  60838. srcX = srcRegion.min.x;
  60839. srcY = srcRegion.min.y;
  60840. srcZ = srcRegion.min.z;
  60841. srcWidth = srcRegion.max.x - srcRegion.min.x;
  60842. srcHeight = srcRegion.max.y - srcRegion.min.y;
  60843. srcDepth = srcRegion.max.z - srcRegion.min.z;
  60844. } else {
  60845. // Assume it's a Box2
  60846. srcX = srcRegion.min.x;
  60847. srcY = srcRegion.min.y;
  60848. srcWidth = srcRegion.max.x - srcRegion.min.x;
  60849. srcHeight = srcRegion.max.y - srcRegion.min.y;
  60850. srcDepth = 1;
  60851. }
  60852. }
  60853. if ( dstPosition !== null ) {
  60854. dstX = dstPosition.x;
  60855. dstY = dstPosition.y;
  60856. dstZ = dstPosition.z || 0;
  60857. }
  60858. _commandEncoderDescriptor.label = 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id;
  60859. const encoder = this.device.createCommandEncoder( _commandEncoderDescriptor );
  60860. _commandEncoderDescriptor.reset();
  60861. const sourceGPU = this.get( srcTexture ).texture;
  60862. const destinationGPU = this.get( dstTexture ).texture;
  60863. _texelCopyTextureInfoSrc.texture = sourceGPU;
  60864. _texelCopyTextureInfoSrc.mipLevel = srcLevel;
  60865. _texelCopyTextureInfoSrc.origin.x = srcX;
  60866. _texelCopyTextureInfoSrc.origin.y = srcY;
  60867. _texelCopyTextureInfoSrc.origin.z = srcZ;
  60868. _texelCopyTextureInfoDst.texture = destinationGPU;
  60869. _texelCopyTextureInfoDst.mipLevel = dstLevel;
  60870. _texelCopyTextureInfoDst.origin.x = dstX;
  60871. _texelCopyTextureInfoDst.origin.y = dstY;
  60872. _texelCopyTextureInfoDst.origin.z = dstZ;
  60873. _extent3D.width = srcWidth;
  60874. _extent3D.height = srcHeight;
  60875. _extent3D.depthOrArrayLayers = srcDepth;
  60876. encoder.copyTextureToTexture(
  60877. _texelCopyTextureInfoSrc,
  60878. _texelCopyTextureInfoDst,
  60879. _extent3D
  60880. );
  60881. _texelCopyTextureInfoSrc.reset();
  60882. _texelCopyTextureInfoDst.reset();
  60883. _extent3D.reset();
  60884. submit( this.device, encoder.finish() );
  60885. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  60886. this.textureUtils.generateMipmaps( dstTexture );
  60887. }
  60888. }
  60889. /**
  60890. * Copies the current bound framebuffer to the given texture.
  60891. *
  60892. * @param {Texture} texture - The destination texture.
  60893. * @param {RenderContext} renderContext - The render context.
  60894. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  60895. */
  60896. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  60897. const renderContextData = this.get( renderContext );
  60898. let sourceGPU = null;
  60899. if ( renderContext.renderTarget ) {
  60900. if ( texture.isDepthTexture ) {
  60901. sourceGPU = this.get( renderContext.depthTexture ).texture;
  60902. } else {
  60903. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  60904. }
  60905. } else {
  60906. if ( texture.isDepthTexture ) {
  60907. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  60908. } else {
  60909. sourceGPU = this.context.getCurrentTexture();
  60910. }
  60911. }
  60912. const destinationGPU = this.get( texture ).texture;
  60913. if ( sourceGPU.format !== destinationGPU.format ) {
  60914. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  60915. return;
  60916. }
  60917. let encoder;
  60918. if ( renderContextData.currentPass ) {
  60919. renderContextData.currentPass.end();
  60920. encoder = renderContextData.encoder;
  60921. } else {
  60922. _commandEncoderDescriptor.label = 'copyFramebufferToTexture_' + texture.id;
  60923. encoder = this.device.createCommandEncoder( _commandEncoderDescriptor );
  60924. _commandEncoderDescriptor.reset();
  60925. }
  60926. _texelCopyTextureInfoSrc.texture = sourceGPU;
  60927. _texelCopyTextureInfoSrc.origin.x = rectangle.x;
  60928. _texelCopyTextureInfoSrc.origin.y = rectangle.y;
  60929. _texelCopyTextureInfoDst.texture = destinationGPU;
  60930. _extent3D.width = rectangle.z;
  60931. _extent3D.height = rectangle.w;
  60932. encoder.copyTextureToTexture(
  60933. _texelCopyTextureInfoSrc,
  60934. _texelCopyTextureInfoDst,
  60935. _extent3D
  60936. );
  60937. _texelCopyTextureInfoSrc.reset();
  60938. _texelCopyTextureInfoDst.reset();
  60939. _extent3D.reset();
  60940. // mipmaps must be genereated with the same encoder otherwise the copied texture data
  60941. // might be out-of-sync, see #31768
  60942. if ( texture.generateMipmaps ) {
  60943. this.textureUtils.generateMipmaps( texture, encoder );
  60944. }
  60945. if ( renderContextData.currentPass ) {
  60946. const { descriptor } = renderContextData;
  60947. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  60948. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  60949. }
  60950. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  60951. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  60952. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  60953. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  60954. if ( renderContext.viewport ) {
  60955. this.updateViewport( renderContext );
  60956. }
  60957. if ( renderContext.scissor ) {
  60958. this.updateScissor( renderContext );
  60959. }
  60960. } else {
  60961. submit( this.device, encoder.finish() );
  60962. }
  60963. }
  60964. /**
  60965. * Checks if the given compatibility is supported by the backend.
  60966. *
  60967. * @param {string} name - The compatibility name.
  60968. * @return {boolean} Whether the compatibility is supported or not.
  60969. */
  60970. hasCompatibility( name ) {
  60971. if ( this._compatibility[ name ] !== undefined ) {
  60972. return this._compatibility[ name ];
  60973. }
  60974. return super.hasCompatibility( name );
  60975. }
  60976. dispose() {
  60977. this.bindingUtils.dispose();
  60978. this.textureUtils.dispose();
  60979. if ( this.occludedResolveCache ) {
  60980. for ( const buffer of this.occludedResolveCache.values() ) {
  60981. buffer.destroy();
  60982. }
  60983. this.occludedResolveCache.clear();
  60984. }
  60985. if ( this.timestampQueryPool ) {
  60986. for ( const queryPool of Object.values( this.timestampQueryPool ) ) {
  60987. if ( queryPool !== null ) queryPool.dispose();
  60988. }
  60989. }
  60990. if ( this.parameters.device === undefined && this.device !== null ) {
  60991. this.device.destroy();
  60992. }
  60993. }
  60994. }
  60995. /**
  60996. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  60997. *
  60998. * @augments SpotLight
  60999. */
  61000. class IESSpotLight extends SpotLight {
  61001. /**
  61002. * Constructs a new IES spot light.
  61003. *
  61004. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  61005. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  61006. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  61007. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  61008. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  61009. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  61010. */
  61011. constructor( color, intensity, distance, angle, penumbra, decay ) {
  61012. super( color, intensity, distance, angle, penumbra, decay );
  61013. /**
  61014. * The IES map. It's a lookup table that stores normalized attenuation factors
  61015. * (0.0 to 1.0) that represent the light's intensity at a specific angle.
  61016. *
  61017. * @type {?Texture}
  61018. * @default null
  61019. */
  61020. this.iesMap = null;
  61021. }
  61022. copy( source, recursive ) {
  61023. super.copy( source, recursive );
  61024. this.iesMap = source.iesMap;
  61025. return this;
  61026. }
  61027. }
  61028. /**
  61029. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  61030. *
  61031. * @augments SpotLight
  61032. */
  61033. class ProjectorLight extends SpotLight {
  61034. /**
  61035. * Constructs a new projector light.
  61036. *
  61037. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  61038. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  61039. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  61040. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  61041. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  61042. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  61043. */
  61044. constructor( color, intensity, distance, angle, penumbra, decay ) {
  61045. super( color, intensity, distance, angle, penumbra, decay );
  61046. /**
  61047. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  61048. *
  61049. * @type {?number}
  61050. * @default null
  61051. */
  61052. this.aspect = null;
  61053. }
  61054. copy( source, recursive ) {
  61055. super.copy( source, recursive );
  61056. this.aspect = source.aspect;
  61057. return this;
  61058. }
  61059. }
  61060. /**
  61061. * This version of a node library represents a basic version
  61062. * just focusing on lights and tone mapping techniques.
  61063. *
  61064. * @private
  61065. * @augments NodeLibrary
  61066. */
  61067. class BasicNodeLibrary extends NodeLibrary {
  61068. /**
  61069. * Constructs a new basic node library.
  61070. */
  61071. constructor() {
  61072. super();
  61073. this.addLight( PointLightNode, PointLight );
  61074. this.addLight( DirectionalLightNode, DirectionalLight );
  61075. this.addLight( RectAreaLightNode, RectAreaLight );
  61076. this.addLight( SpotLightNode, SpotLight );
  61077. this.addLight( AmbientLightNode, AmbientLight );
  61078. this.addLight( HemisphereLightNode, HemisphereLight );
  61079. this.addLight( LightProbeNode, LightProbe );
  61080. this.addLight( IESSpotLightNode, IESSpotLight );
  61081. this.addLight( ProjectorLightNode, ProjectorLight );
  61082. this.addToneMapping( linearToneMapping, LinearToneMapping );
  61083. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  61084. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  61085. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  61086. this.addToneMapping( agxToneMapping, AgXToneMapping );
  61087. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  61088. }
  61089. }
  61090. /**
  61091. * This alternative version of {@link WebGPURenderer} only supports node materials.
  61092. * So classes like `MeshBasicMaterial` are not compatible.
  61093. *
  61094. * @private
  61095. * @augments Renderer
  61096. */
  61097. class WebGPURenderer extends Renderer {
  61098. /**
  61099. * Constructs a new WebGPU renderer.
  61100. *
  61101. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  61102. */
  61103. constructor( parameters = {} ) {
  61104. let BackendClass;
  61105. if ( parameters.forceWebGL ) {
  61106. BackendClass = WebGLBackend;
  61107. } else {
  61108. BackendClass = WebGPUBackend;
  61109. parameters.getFallback = () => {
  61110. warn( 'WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  61111. return new WebGLBackend( parameters );
  61112. };
  61113. }
  61114. const backend = new BackendClass( parameters );
  61115. super( backend, parameters );
  61116. /**
  61117. * The generic default value is overwritten with the
  61118. * standard node library for type mapping. Material
  61119. * mapping is not supported with this version.
  61120. *
  61121. * @type {BasicNodeLibrary}
  61122. */
  61123. this.library = new BasicNodeLibrary();
  61124. /**
  61125. * This flag can be used for type testing.
  61126. *
  61127. * @type {boolean}
  61128. * @readonly
  61129. * @default true
  61130. */
  61131. this.isWebGPURenderer = true;
  61132. }
  61133. }
  61134. /**
  61135. * A specialized group which enables applications access to the
  61136. * Render Bundle API of WebGPU. The group with all its descendant nodes
  61137. * are considered as one render bundle and processed as such by
  61138. * the renderer.
  61139. *
  61140. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  61141. * With a WebGL backend, the group can technically be rendered but without
  61142. * any performance improvements.
  61143. *
  61144. * @augments Group
  61145. */
  61146. class BundleGroup extends Group {
  61147. /**
  61148. * Constructs a new bundle group.
  61149. */
  61150. constructor() {
  61151. super();
  61152. /**
  61153. * This flag can be used for type testing.
  61154. *
  61155. * @type {boolean}
  61156. * @readonly
  61157. * @default true
  61158. */
  61159. this.isBundleGroup = true;
  61160. /**
  61161. * This property is only relevant for detecting types
  61162. * during serialization/deserialization. It should always
  61163. * match the class name.
  61164. *
  61165. * @type {string}
  61166. * @readonly
  61167. * @default 'BundleGroup'
  61168. */
  61169. this.type = 'BundleGroup';
  61170. /**
  61171. * Whether the bundle is static or not. When set to `true`, the structure
  61172. * is assumed to be static and does not change. E.g. no new objects are
  61173. * added to the group.
  61174. *
  61175. * If a change is required, an update can still be forced by setting the
  61176. * `needsUpdate` flag to `true`.
  61177. *
  61178. * @type {boolean}
  61179. * @default true
  61180. */
  61181. this.static = true;
  61182. /**
  61183. * The bundle group's version.
  61184. *
  61185. * @type {number}
  61186. * @readonly
  61187. * @default 0
  61188. */
  61189. this.version = 0;
  61190. }
  61191. /**
  61192. * Set this property to `true` when the bundle group has changed.
  61193. *
  61194. * @type {boolean}
  61195. * @default false
  61196. * @param {boolean} value
  61197. */
  61198. set needsUpdate( value ) {
  61199. if ( value === true ) this.version ++;
  61200. }
  61201. }
  61202. /**
  61203. * This module is responsible to manage the rendering pipeline setups in apps.
  61204. * You usually create a single instance of this class and use it to define
  61205. * the output of your render pipeline and post processing effect chain.
  61206. * ```js
  61207. * const renderPipeline = new RenderPipeline( renderer );
  61208. *
  61209. * const scenePass = pass( scene, camera );
  61210. *
  61211. * renderPipeline.outputNode = scenePass;
  61212. * ```
  61213. *
  61214. * Note: This module can only be used with `WebGPURenderer`.
  61215. */
  61216. class RenderPipeline {
  61217. /**
  61218. * Constructs a new render pipeline management module.
  61219. *
  61220. * @param {Renderer} renderer - A reference to the renderer.
  61221. * @param {Node<vec4>} outputNode - An optional output node.
  61222. */
  61223. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  61224. /**
  61225. * A reference to the renderer.
  61226. *
  61227. * @type {Renderer}
  61228. */
  61229. this.renderer = renderer;
  61230. /**
  61231. * A node which defines the final output of the rendering
  61232. * pipeline. This is usually the last node in a chain
  61233. * of effect nodes.
  61234. *
  61235. * @type {Node<vec4>}
  61236. */
  61237. this.outputNode = outputNode;
  61238. /**
  61239. * Whether the default output tone mapping and color
  61240. * space transformation should be enabled or not.
  61241. *
  61242. * This is enabled by default but it must be disabled for
  61243. * effects that expect to be executed after tone mapping and color
  61244. * space conversion. A typical example is FXAA which
  61245. * requires sRGB input.
  61246. *
  61247. * When set to `false`, the app must control the output
  61248. * transformation with `RenderOutputNode`.
  61249. *
  61250. * ```js
  61251. * const outputPass = renderOutput( scenePass );
  61252. * ```
  61253. *
  61254. * @type {boolean}
  61255. */
  61256. this.outputColorTransform = true;
  61257. /**
  61258. * Must be set to `true` when the output node changes.
  61259. *
  61260. * @type {Node<vec4>}
  61261. */
  61262. this.needsUpdate = true;
  61263. const material = new NodeMaterial();
  61264. material.name = 'RenderPipeline';
  61265. /**
  61266. * The full screen quad that is used to render
  61267. * the effects.
  61268. *
  61269. * @private
  61270. * @type {QuadMesh}
  61271. */
  61272. this._quadMesh = new QuadMesh( material );
  61273. this._quadMesh.name = 'Render Pipeline';
  61274. /**
  61275. * The context of the render pipeline stack.
  61276. *
  61277. * @private
  61278. * @type {?Object}
  61279. * @default null
  61280. */
  61281. this._context = null;
  61282. /**
  61283. * The current tone mapping.
  61284. *
  61285. * @private
  61286. * @type {ToneMapping}
  61287. */
  61288. this._toneMapping = renderer.toneMapping;
  61289. /**
  61290. * The current output color space.
  61291. *
  61292. * @private
  61293. * @type {ColorSpace}
  61294. */
  61295. this._outputColorSpace = renderer.outputColorSpace;
  61296. }
  61297. /**
  61298. * When `RenderPipeline` is used to apply rendering pipeline and post processing effects,
  61299. * the application must use this version of `render()` inside
  61300. * its animation loop (not the one from the renderer).
  61301. */
  61302. render() {
  61303. const renderer = this.renderer;
  61304. this._update();
  61305. if ( this._context.onBeforeRenderPipeline !== null ) this._context.onBeforeRenderPipeline();
  61306. const toneMapping = renderer.toneMapping;
  61307. const outputColorSpace = renderer.outputColorSpace;
  61308. renderer.toneMapping = NoToneMapping;
  61309. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  61310. //
  61311. const currentXR = renderer.xr.enabled;
  61312. renderer.xr.enabled = false;
  61313. this._quadMesh.render( renderer );
  61314. renderer.xr.enabled = currentXR;
  61315. //
  61316. renderer.toneMapping = toneMapping;
  61317. renderer.outputColorSpace = outputColorSpace;
  61318. if ( this._context.onAfterRenderPipeline !== null ) this._context.onAfterRenderPipeline();
  61319. }
  61320. /**
  61321. * Returns the current context of the render pipeline stack.
  61322. *
  61323. * @readonly
  61324. * @type {?Object}
  61325. */
  61326. get context() {
  61327. return this._context;
  61328. }
  61329. /**
  61330. * Frees internal resources.
  61331. */
  61332. dispose() {
  61333. this._quadMesh.material.dispose();
  61334. }
  61335. /**
  61336. * Updates the state of the module.
  61337. *
  61338. * @private
  61339. */
  61340. _update() {
  61341. if ( this._toneMapping !== this.renderer.toneMapping ) {
  61342. this._toneMapping = this.renderer.toneMapping;
  61343. this.needsUpdate = true;
  61344. }
  61345. if ( this._outputColorSpace !== this.renderer.outputColorSpace ) {
  61346. this._outputColorSpace = this.renderer.outputColorSpace;
  61347. this.needsUpdate = true;
  61348. }
  61349. if ( this.needsUpdate === true ) {
  61350. const toneMapping = this._toneMapping;
  61351. const outputColorSpace = this._outputColorSpace;
  61352. const context = {
  61353. renderPipeline: this,
  61354. onBeforeRenderPipeline: null,
  61355. onAfterRenderPipeline: null
  61356. };
  61357. let outputNode = this.outputNode;
  61358. if ( this.outputColorTransform === true ) {
  61359. outputNode = outputNode.context( context );
  61360. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  61361. } else {
  61362. context.toneMapping = toneMapping;
  61363. context.outputColorSpace = outputColorSpace;
  61364. outputNode = outputNode.context( context );
  61365. }
  61366. this._context = context;
  61367. this._quadMesh.material.fragmentNode = outputNode;
  61368. this._quadMesh.material.needsUpdate = true;
  61369. this.needsUpdate = false;
  61370. }
  61371. }
  61372. /**
  61373. * When `RenderPipeline` is used to apply rendering pipeline and post processing effects,
  61374. * the application must use this version of `renderAsync()` inside
  61375. * its animation loop (not the one from the renderer).
  61376. *
  61377. * @async
  61378. * @deprecated
  61379. * @return {Promise} A Promise that resolves when the render has been finished.
  61380. */
  61381. async renderAsync() {
  61382. warnOnce( 'RenderPipeline: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  61383. await this.renderer.init();
  61384. this.render();
  61385. }
  61386. }
  61387. /**
  61388. * @deprecated since r183. Use {@link RenderPipeline} instead. PostProcessing has been renamed to RenderPipeline.
  61389. *
  61390. * This class is a wrapper for backward compatibility and will be removed in a future version.
  61391. */
  61392. class PostProcessing extends RenderPipeline {
  61393. /**
  61394. * Constructs a new post processing management module.
  61395. *
  61396. * @param {Renderer} renderer - A reference to the renderer.
  61397. * @param {Node<vec4>} outputNode - An optional output node.
  61398. * @deprecated since r183. Use {@link RenderPipeline} instead.
  61399. */
  61400. constructor( renderer, outputNode ) {
  61401. warnOnce( 'PostProcessing: "PostProcessing" has been renamed to "RenderPipeline". Please update your code to use "THREE.RenderPipeline" instead.' ); // @deprecated, r183
  61402. super( renderer, outputNode );
  61403. }
  61404. }
  61405. /**
  61406. * A readback buffer is used to transfer data from the GPU to the CPU.
  61407. * It is primarily used to read back compute shader results.
  61408. *
  61409. * @augments EventDispatcher
  61410. */
  61411. class ReadbackBuffer extends EventDispatcher {
  61412. /**
  61413. * Constructs a new readback buffer.
  61414. *
  61415. * @param {number} maxByteLength - The maximum size of the buffer to be read back.
  61416. */
  61417. constructor( maxByteLength ) {
  61418. super();
  61419. /**
  61420. * Name used for debugging purposes.
  61421. *
  61422. * @type {string}
  61423. */
  61424. this.name = '';
  61425. /**
  61426. * The mapped, read back array buffer.
  61427. *
  61428. * @type {ArrayBuffer|null}
  61429. */
  61430. this.buffer = null;
  61431. /**
  61432. * The maximum size of the buffer to be read back.
  61433. *
  61434. * @type {number}
  61435. */
  61436. this.maxByteLength = maxByteLength;
  61437. /**
  61438. * This flag can be used for type testing.
  61439. *
  61440. * @type {boolean}
  61441. * @readonly
  61442. * @default true
  61443. */
  61444. this.isReadbackBuffer = true;
  61445. this._mapped = false;
  61446. }
  61447. /**
  61448. * Releases the mapped buffer data so the GPU buffer can be
  61449. * used by the GPU again.
  61450. *
  61451. * Note: Any `ArrayBuffer` data associated with this readback buffer
  61452. * are removed and no longer accessible after calling this method.
  61453. */
  61454. release() {
  61455. this.dispatchEvent( { type: 'release' } );
  61456. }
  61457. /**
  61458. * Frees internal resources.
  61459. */
  61460. dispose() {
  61461. this.dispatchEvent( { type: 'dispose' } );
  61462. }
  61463. }
  61464. /**
  61465. * This special type of texture is intended for compute shaders.
  61466. * It can be used to compute the data of a texture with a compute shader.
  61467. *
  61468. * Note: This type of texture can only be used with `WebGPURenderer`
  61469. * and a WebGPU backend.
  61470. *
  61471. * @augments Texture
  61472. */
  61473. class StorageTexture extends Texture {
  61474. /**
  61475. * Constructs a new storage texture.
  61476. *
  61477. * @param {number} [width=1] - The storage texture's width.
  61478. * @param {number} [height=1] - The storage texture's height.
  61479. */
  61480. constructor( width = 1, height = 1 ) {
  61481. super();
  61482. /**
  61483. * The image object which just represents the texture's dimension.
  61484. *
  61485. * @type {{width: number, height: number}}
  61486. */
  61487. this.image = { width, height };
  61488. /**
  61489. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  61490. *
  61491. * @type {number}
  61492. */
  61493. this.magFilter = LinearFilter;
  61494. /**
  61495. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  61496. *
  61497. * @type {number}
  61498. */
  61499. this.minFilter = LinearFilter;
  61500. /**
  61501. * This flag can be used for type testing.
  61502. *
  61503. * @type {boolean}
  61504. * @readonly
  61505. * @default true
  61506. */
  61507. this.isStorageTexture = true;
  61508. /**
  61509. * When `true`, mipmaps will be auto-generated after compute writes.
  61510. * When `false`, mipmaps must be written manually via compute shaders.
  61511. *
  61512. * @type {boolean}
  61513. * @default true
  61514. */
  61515. this.mipmapsAutoUpdate = true;
  61516. }
  61517. /**
  61518. * Sets the size of the storage texture.
  61519. *
  61520. * @param {number} width - The new width of the storage texture.
  61521. * @param {number} height - The new height of the storage texture.
  61522. */
  61523. setSize( width, height ) {
  61524. if ( this.image.width !== width || this.image.height !== height ) {
  61525. this.image.width = width;
  61526. this.image.height = height;
  61527. this.dispose();
  61528. }
  61529. }
  61530. }
  61531. /**
  61532. * This special type of buffer attribute is intended for compute shaders.
  61533. * It can be used to encode draw parameters for indirect draw calls.
  61534. *
  61535. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  61536. * and a WebGPU backend.
  61537. *
  61538. * @augments StorageBufferAttribute
  61539. */
  61540. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  61541. /**
  61542. * Constructs a new storage buffer attribute.
  61543. *
  61544. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  61545. * The subsequent parameter is then obsolete.
  61546. * @param {number} itemSize - The item size.
  61547. */
  61548. constructor( count, itemSize ) {
  61549. super( count, itemSize, Uint32Array );
  61550. /**
  61551. * This flag can be used for type testing.
  61552. *
  61553. * @type {boolean}
  61554. * @readonly
  61555. * @default true
  61556. */
  61557. this.isIndirectStorageBufferAttribute = true;
  61558. }
  61559. }
  61560. /**
  61561. * A loader for loading node objects in the three.js JSON Object/Scene format.
  61562. *
  61563. * @augments Loader
  61564. */
  61565. class NodeLoader extends Loader {
  61566. /**
  61567. * Constructs a new node loader.
  61568. *
  61569. * @param {LoadingManager} [manager] - A reference to a loading manager.
  61570. */
  61571. constructor( manager ) {
  61572. super( manager );
  61573. /**
  61574. * Represents a dictionary of textures.
  61575. *
  61576. * @type {Object<string,Texture>}
  61577. */
  61578. this.textures = {};
  61579. /**
  61580. * Represents a dictionary of node types.
  61581. *
  61582. * @type {Object<string,Node.constructor>}
  61583. */
  61584. this.nodes = {};
  61585. }
  61586. /**
  61587. * Loads the node definitions from the given URL.
  61588. *
  61589. * @param {string} url - The path/URL of the file to be loaded.
  61590. * @param {Function} onLoad - Will be called when load completes.
  61591. * @param {Function} onProgress - Will be called while load progresses.
  61592. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  61593. */
  61594. load( url, onLoad, onProgress, onError ) {
  61595. const loader = new FileLoader( this.manager );
  61596. loader.setPath( this.path );
  61597. loader.setRequestHeader( this.requestHeader );
  61598. loader.setWithCredentials( this.withCredentials );
  61599. loader.load( url, ( text ) => {
  61600. try {
  61601. onLoad( this.parse( JSON.parse( text ) ) );
  61602. } catch ( e ) {
  61603. if ( onError ) {
  61604. onError( e );
  61605. } else {
  61606. error( e );
  61607. }
  61608. this.manager.itemError( url );
  61609. }
  61610. }, onProgress, onError );
  61611. }
  61612. /**
  61613. * Parse the node dependencies for the loaded node.
  61614. *
  61615. * @param {Array<Object>} [json] - The JSON definition
  61616. * @return {Object<string,Node>} A dictionary with node dependencies.
  61617. */
  61618. parseNodes( json ) {
  61619. const nodes = {};
  61620. if ( json !== undefined ) {
  61621. for ( const nodeJSON of json ) {
  61622. const { uuid, type } = nodeJSON;
  61623. nodes[ uuid ] = this.createNodeFromType( type );
  61624. nodes[ uuid ].uuid = uuid;
  61625. }
  61626. const meta = { nodes, textures: this.textures };
  61627. for ( const nodeJSON of json ) {
  61628. nodeJSON.meta = meta;
  61629. const node = nodes[ nodeJSON.uuid ];
  61630. node.deserialize( nodeJSON );
  61631. delete nodeJSON.meta;
  61632. }
  61633. }
  61634. return nodes;
  61635. }
  61636. /**
  61637. * Parses the node from the given JSON.
  61638. *
  61639. * @param {Object} json - The JSON definition
  61640. * @param {string} json.type - The node type.
  61641. * @param {string} json.uuid - The node UUID.
  61642. * @param {Array<Object>} [json.nodes] - The node dependencies.
  61643. * @param {Object} [json.meta] - The meta data.
  61644. * @return {Node} The parsed node.
  61645. */
  61646. parse( json ) {
  61647. const node = this.createNodeFromType( json.type );
  61648. node.uuid = json.uuid;
  61649. const nodes = this.parseNodes( json.nodes );
  61650. const meta = { nodes, textures: this.textures };
  61651. json.meta = meta;
  61652. node.deserialize( json );
  61653. delete json.meta;
  61654. return node;
  61655. }
  61656. /**
  61657. * Defines the dictionary of textures.
  61658. *
  61659. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  61660. * @return {NodeLoader} A reference to this loader.
  61661. */
  61662. setTextures( value ) {
  61663. this.textures = value;
  61664. return this;
  61665. }
  61666. /**
  61667. * Defines the dictionary of node types.
  61668. *
  61669. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  61670. * @return {NodeLoader} A reference to this loader.
  61671. */
  61672. setNodes( value ) {
  61673. this.nodes = value;
  61674. return this;
  61675. }
  61676. /**
  61677. * Creates a node object from the given type.
  61678. *
  61679. * @param {string} type - The node type.
  61680. * @return {Node} The created node instance.
  61681. */
  61682. createNodeFromType( type ) {
  61683. if ( this.nodes[ type ] === undefined ) {
  61684. error( 'NodeLoader: Node type not found:', type );
  61685. return float();
  61686. }
  61687. return new this.nodes[ type ]();
  61688. }
  61689. }
  61690. /**
  61691. * A special type of material loader for loading node materials.
  61692. *
  61693. * @augments MaterialLoader
  61694. */
  61695. class NodeMaterialLoader extends MaterialLoader {
  61696. /**
  61697. * Constructs a new node material loader.
  61698. *
  61699. * @param {LoadingManager} [manager] - A reference to a loading manager.
  61700. */
  61701. constructor( manager ) {
  61702. super( manager );
  61703. /**
  61704. * Represents a dictionary of node types.
  61705. *
  61706. * @type {Object<string,Node.constructor>}
  61707. */
  61708. this.nodes = {};
  61709. /**
  61710. * Represents a dictionary of node material types.
  61711. *
  61712. * @type {Object<string,NodeMaterial.constructor>}
  61713. */
  61714. this.nodeMaterials = {};
  61715. }
  61716. /**
  61717. * Parses the node material from the given JSON.
  61718. *
  61719. * @param {Object} json - The JSON definition
  61720. * @return {NodeMaterial}. The parsed material.
  61721. */
  61722. parse( json ) {
  61723. const material = super.parse( json );
  61724. const nodes = this.nodes;
  61725. const inputNodes = json.inputNodes;
  61726. for ( const property in inputNodes ) {
  61727. const uuid = inputNodes[ property ];
  61728. material[ property ] = nodes[ uuid ];
  61729. }
  61730. return material;
  61731. }
  61732. /**
  61733. * Defines the dictionary of node types.
  61734. *
  61735. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  61736. * @return {NodeLoader} A reference to this loader.
  61737. */
  61738. setNodes( value ) {
  61739. this.nodes = value;
  61740. return this;
  61741. }
  61742. /**
  61743. * Defines the dictionary of node material types.
  61744. *
  61745. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  61746. * @return {NodeLoader} A reference to this loader.
  61747. */
  61748. setNodeMaterials( value ) {
  61749. this.nodeMaterials = value;
  61750. return this;
  61751. }
  61752. /**
  61753. * Creates a node material from the given type.
  61754. *
  61755. * @param {string} type - The node material type.
  61756. * @return {Node} The created node material instance.
  61757. */
  61758. createMaterialFromType( type ) {
  61759. const materialClass = this.nodeMaterials[ type ];
  61760. if ( materialClass !== undefined ) {
  61761. return new materialClass();
  61762. }
  61763. return super.createMaterialFromType( type );
  61764. }
  61765. }
  61766. /**
  61767. * A special type of object loader for loading 3D objects using
  61768. * node materials.
  61769. *
  61770. * @augments ObjectLoader
  61771. */
  61772. class NodeObjectLoader extends ObjectLoader {
  61773. /**
  61774. * Constructs a new node object loader.
  61775. *
  61776. * @param {LoadingManager} [manager] - A reference to a loading manager.
  61777. */
  61778. constructor( manager ) {
  61779. super( manager );
  61780. /**
  61781. * Represents a dictionary of node types.
  61782. *
  61783. * @type {Object<string,Node.constructor>}
  61784. */
  61785. this.nodes = {};
  61786. /**
  61787. * Represents a dictionary of node material types.
  61788. *
  61789. * @type {Object<string,NodeMaterial.constructor>}
  61790. */
  61791. this.nodeMaterials = {};
  61792. /**
  61793. * A reference to hold the `nodes` JSON property.
  61794. *
  61795. * @private
  61796. * @type {?Object[]}
  61797. */
  61798. this._nodesJSON = null;
  61799. }
  61800. /**
  61801. * Defines the dictionary of node types.
  61802. *
  61803. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  61804. * @return {NodeObjectLoader} A reference to this loader.
  61805. */
  61806. setNodes( value ) {
  61807. this.nodes = value;
  61808. return this;
  61809. }
  61810. /**
  61811. * Defines the dictionary of node material types.
  61812. *
  61813. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  61814. * @return {NodeObjectLoader} A reference to this loader.
  61815. */
  61816. setNodeMaterials( value ) {
  61817. this.nodeMaterials = value;
  61818. return this;
  61819. }
  61820. /**
  61821. * Parses the node objects from the given JSON.
  61822. *
  61823. * @param {Object} json - The JSON definition
  61824. * @param {Function} onLoad - The onLoad callback function.
  61825. * @return {Object3D}. The parsed 3D object.
  61826. */
  61827. parse( json, onLoad ) {
  61828. this._nodesJSON = json.nodes;
  61829. const data = super.parse( json, onLoad );
  61830. this._nodesJSON = null; // dispose
  61831. return data;
  61832. }
  61833. /**
  61834. * Async version of {@link NodeObjectLoader#parse}.
  61835. *
  61836. * @param {Object} json - The JSON definition
  61837. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  61838. */
  61839. async parseAsync( json ) {
  61840. this._nodesJSON = json.nodes;
  61841. const data = await super.parseAsync( json );
  61842. this._nodesJSON = null; // dispose
  61843. return data;
  61844. }
  61845. /**
  61846. * Parses the node objects from the given JSON and textures.
  61847. *
  61848. * @param {Object[]} json - The JSON definition
  61849. * @param {Object<string,Texture>} textures - The texture library.
  61850. * @return {Object<string,Node>}. The parsed nodes.
  61851. */
  61852. parseNodes( json, textures ) {
  61853. if ( json !== undefined ) {
  61854. const loader = new NodeLoader();
  61855. loader.setNodes( this.nodes );
  61856. loader.setTextures( textures );
  61857. return loader.parseNodes( json );
  61858. }
  61859. return {};
  61860. }
  61861. /**
  61862. * Parses the node objects from the given JSON and textures.
  61863. *
  61864. * @param {Object} json - The JSON definition
  61865. * @param {Object<string,Texture>} textures - The texture library.
  61866. * @return {Object<string,NodeMaterial>}. The parsed materials.
  61867. */
  61868. parseMaterials( json, textures ) {
  61869. const materials = {};
  61870. if ( json !== undefined ) {
  61871. const nodes = this.parseNodes( this._nodesJSON, textures );
  61872. const loader = new NodeMaterialLoader();
  61873. loader.setTextures( textures );
  61874. loader.setNodes( nodes );
  61875. loader.setNodeMaterials( this.nodeMaterials );
  61876. for ( let i = 0, l = json.length; i < l; i ++ ) {
  61877. const data = json[ i ];
  61878. materials[ data.uuid ] = loader.parse( data );
  61879. }
  61880. }
  61881. return materials;
  61882. }
  61883. }
  61884. /**
  61885. * In earlier three.js versions, clipping was defined globally
  61886. * on the renderer or on material level. This special version of
  61887. * `THREE.Group` allows to encode the clipping state into the scene
  61888. * graph. Meaning if you create an instance of this group, all
  61889. * descendant 3D objects will be affected by the respective clipping
  61890. * planes.
  61891. *
  61892. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  61893. *
  61894. * @augments Group
  61895. */
  61896. class ClippingGroup extends Group {
  61897. /**
  61898. * Constructs a new clipping group.
  61899. */
  61900. constructor() {
  61901. super();
  61902. /**
  61903. * This flag can be used for type testing.
  61904. *
  61905. * @type {boolean}
  61906. * @readonly
  61907. * @default true
  61908. */
  61909. this.isClippingGroup = true;
  61910. /**
  61911. * An array with clipping planes.
  61912. *
  61913. * @type {Array<Plane>}
  61914. */
  61915. this.clippingPlanes = [];
  61916. /**
  61917. * Whether clipping should be enabled or not.
  61918. *
  61919. * @type {boolean}
  61920. * @default true
  61921. */
  61922. this.enabled = true;
  61923. /**
  61924. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  61925. *
  61926. * @type {boolean}
  61927. * @default false
  61928. */
  61929. this.clipIntersection = false;
  61930. /**
  61931. * Whether shadows should be clipped or not.
  61932. *
  61933. * @type {boolean}
  61934. * @default false
  61935. */
  61936. this.clipShadows = false;
  61937. }
  61938. }
  61939. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AtomicFunctionNode, AttributeNode, BackSide, BarrierNode, BasicEnvironmentNode, BasicLightMapNode, 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, 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, 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, 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, StaticDrawUsage, StorageArrayElementNode, 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, WebGLBackend, WebGLCoordinateSystem, WebGPUBackend, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, WorkgroupInfoNode, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, error, log$1 as log, shaderStages, vectorComponents, warn, warnOnce };
粤ICP备19079148号